码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-10-17 22:54:59      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:document   简单的   var   htm   一个   简单   服务   cli   cal   

客户端:

 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实现一个简单的聊天室功能

标签:document   简单的   var   htm   一个   简单   服务   cli   cal   

原文地址:http://www.cnblogs.com/xiedashuaige/p/7684213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!