nodejs+websocket简单的聊天窗口
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>