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

2021-05-23 17:29

阅读:529

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

客户端:

 1 DOCTYPE html>
 2 html>
 3 head>
 4     meta charset="utf-8" />
 5     title>websokettitle>
 6 head>
 7 body>
 8     h1>chat roomh1>
 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


评论


亲,登录后才可以留言!