1、node中使用websocket需要導入 nodejs-websocket 模塊 ,全局下載 nodejs-websocket
cnpm install nodejs-websocket --save -g
2、nodejs
let ws = require("nodejs-websocket");
process.stdin.setEncoding('utf8');
console.log("開始建立連接...");
let send ='初始值';
let user1=null;
let user2=null;
let user1Ready=false;
let user2Ready=false;
let server = ws.createServer(function(conn){
conn.on("text", function (str) {
let newStr=eval('('+str+')');
console.log("收到的信息為:"+newStr.sendNuber)
console.log("用戶:"+newStr.name);
if(newStr.name==="userName1"){
user1 = conn;
user1Ready = true;
}
if(newStr.name==="userName2"){
user2 = conn;
user2Ready = true;
}
//兩個聊天窗口就已經建立了連接
if(user1Ready&&user2Ready){
user2.sendText(newStr.name+':'+newStr.sendNuber);
user1.sendText(newStr.name+':'+newStr.sendNuber);
}else {
conn.sendText(newStr.name+':'+newStr.sendNuber)
}
//像前端頁面發送推送
process.stdout.write('請輸入發送的值:');
process.stdin.on('data',function (chunk) {
conn.sendText(chunk)
});
});
conn.on("close", function (code, reason) {
console.log("關閉連接")
});
conn.on("error", function (code, reason) {
console.log("異常關閉")
});
}).listen(8801)
console.log("WebSocket建立完畢")
3、用戶1的頁面
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>websocket(用戶1)</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script type="text/javascript"> function WebSocketTest() { if ("WebSocket" in window) { console.log("您的瀏覽器支持 WebSocket!"); // 打開一個 web socket var ws = new WebSocket("ws://127.0.0.1:8801/"); ws.onopen = function() { // Web Socket 已連接上,使用 send() 方法發送數據 ws.send("{name:'userName1',sendNuber:'已經建立連接'}"); console.log("數據發送中..."); document.getElementById('Bridge').style.display='none' }; ws.onmessage = function (evt) { var received_msg = evt.data; console.log(received_msg) /* document.getElementById('div').innerHTML +=received_msg*/ var li = document.createElement("li"); li.innerHTML=received_msg; if(received_msg.indexOf('userName1')>-1){ li.setAttribute("style", 'color: #E91E63;font-weight: 700;text-align: right;'); }else{ li.setAttribute("style", 'color: #2196F3;font-weight: 700;'); } document.getElementById('chat-list').appendChild(li) console.log("數據已接收..."); document.querySelector("#btnSend").onclick = function(e){ var chatBox =document.getElementById('chatBox').value; // Web Socket 已連接上,使用 send() 方法發送數據 ws.send("{name:'userName1',sendNuber:'"+chatBox+"'}"); document.getElementById('chatBox').value =''; } }; ws.onclose = function() { // 關閉 websocket alert("連接已關閉..."); document.getElementById('Bridge').style.display='block' }; } else { // 瀏覽器不支持 WebSocket alert("您的瀏覽器不支持 WebSocket!"); } } </script> </head> <body> <div class="col-sm-6"> <ul id="chat-list"></ul> <div class="form-group"> <p></p> <textarea id="chatBox" class="col-sm-2 form-control" rows="3" style="margin-bottom:10px"></textarea> <button type="button" onclick="WebSocketTest()" class="btn btn-primary" id="Bridge" style="float: left;margin-right: 10px">建立連接</button> <button type="button" id='btnSend' class="btn btn-success">發送信息</button> </div> </div> </body> </html>
4、用戶2的頁面
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>websocket(用戶2)</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script type="text/javascript"> function WebSocketTest() { if ("WebSocket" in window) { console.log("您的瀏覽器支持 WebSocket!"); // 打開一個 web socket var ws = new WebSocket("ws://127.0.0.1:8801/"); ws.onopen = function() { // Web Socket 已連接上,使用 send() 方法發送數據 ws.send("{name:'userName2',sendNuber:'已經建立連接'}"); console.log("數據發送中..."); document.getElementById('Bridge').style.display='none' }; ws.onmessage = function (evt) { var received_msg = evt.data; console.log(received_msg) /* document.getElementById('div').innerHTML +=received_msg*/ var li = document.createElement("li"); li.innerHTML=received_msg; if(received_msg.indexOf('userName1')>-1){ li.setAttribute("style", 'color: #E91E63;font-weight: 700;'); }else{ li.setAttribute("style", 'color: #2196F3;font-weight: 700;text-align: right;'); } document.getElementById('chat-list').appendChild(li) console.log("數據已接收..."); document.querySelector("#btnSend").onclick = function(e){ var chatBox =document.getElementById('chatBox').value; // Web Socket 已連接上,使用 send() 方法發送數據 ws.send("{name:'userName2',sendNuber:'"+chatBox+"'}"); document.getElementById('chatBox').value =''; } }; ws.onclose = function() { // 關閉 websocket alert("連接已關閉..."); document.getElementById('Bridge').style.display='block' }; } else { // 瀏覽器不支持 WebSocket alert("您的瀏覽器不支持 WebSocket!"); } } </script> </head> <body> <div class="col-sm-6"> <ul id="chat-list"></ul> <div class="form-group"> <p></p> <textarea id="chatBox" class="col-sm-2 form-control" rows="3" style="margin-bottom:10px"></textarea> <button type="button" onclick="WebSocketTest()" class="btn btn-primary" id="Bridge" style="float: left;margin-right: 10px">建立連接</button> <button type="button" id='btnSend' class="btn btn-success">發送信息</button> </div> </div> </body> </html>
