通过WebSocket实现一个简单的聊天室功能

WebSocket

WebSocket是一个协议,它是是基于TCP的一种新的网络协议,TCP协议是一种持续性的协议,和HTTP不同的是,它可以在服务器端主动向客户端推送消息。通过这个协议,可以在建立一个nodejs的服务器,然后所有的客户端都可以向服务器端发送消息,然后服务器端把这个消息广播出去,形成了一个类似于聊天室的东西。

客户端:

 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>

从我的服务器localhost:6666实例化一个新的websocket,然后打开他监听发送按钮,点击发送就把txt发送到服务器端,然后监听得到的消息,通过showMsg渲染到界面上去

服务器端(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 }

 之前要加载一下nodejs-websocket模块,来一个人就把计数器加1,然后给他设置名字,监听收到的消息text,有消息就执行broadcast,broadcast就是向所有的客户端广播新的消息

举个例子

这里是我服务器上的栗子,大家可以看看

http://www.xiedashuaige.cn/websocket.html

posted @ 2017-10-17 22:03  谢大帅哥  阅读(1727)  评论(11编辑  收藏  举报