通过WebSocket实现一个简单的聊天室功能
Posted 谢大帅哥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过WebSocket实现一个简单的聊天室功能相关的知识,希望对你有一定的参考价值。
客户端:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>websoket</title> 6 </head> 7 <body> 8 <h1>chat room</h1> 9 <input type="text" id="msg" /> 10 <button id="send">发送</button> 11 <script type="text/javascript"> 12 var websocket = new WebSocket("ws://localhost:6666/"); 13 14 function showMsg(str){ 15 var div = document.createElement(‘div‘); 16 div.innerHTML = str; 17 document.body.appendChild(div) 18 } 19 20 websocket.onopen=function(){ 21 console.log("open"); 22 document.getElementById(‘send‘).onclick = function() { 23 var txt = document.getElementById(‘msg‘).value; 24 if (txt) { 25 websocket.send(txt); 26 } 27 } 28 } 29 websocket.onclose = function() { 30 console.log("close"); 31 } 32 websocket.onmessage = function(e) { 33 console.log(e.data); 34 showMsg(e.data); 35 } 36 </script> 37 </body> 38 </html>
服务器端(node.js):
1 var ws = require("nodejs-websocket") 2 3 var port = 6666; 4 5 var clientCount = 0; 6 7 var server = ws.createServer(function (conn) { 8 console.log("New connection") 9 clientCount++ 10 conn.nickname = "user" + clientCount 11 broadcast("******* "+conn.nickname + " comes in *******"); 12 13 14 conn.on("text", function (str) { 15 console.log("Received "+str) 16 broadcast(conn.nickname + " say: " + str) 17 }) 18 19 20 conn.on("close", function (code, reason) { 21 broadcast("******* " + conn.nickname + " left *******"); 22 }) 23 conn.on("error", function(err) { 24 console.log("error: "+err); 25 }) 26 }).listen(port) 27 28 console.log("websocket server listening on " + port); 29 30 function broadcast (str) { 31 server.connections.forEach(function (connection) { 32 connection.sendText(str) 33 }) 34 }
以上是关于通过WebSocket实现一个简单的聊天室功能的主要内容,如果未能解决你的问题,请参考以下文章
WebSocket入门教程-- WebSocket实例:简单多人聊天室