首页 > 代码库 > node+ws模块实现websocket

node+ws模块实现websocket

先来吐槽一下,想要找点技术文章真tm不容易,全是jb复制粘贴,还冒充原创。搜索一个ws实现websocket全是一样的。一个字都没变,我能说什么。最后想到搜索ws模块githup居然前两页没有,也是那些重复的文章,无力吐槽。奉上一个githup上面的(虽然全是英文的,但是绝壁比那些复制粘贴的好)https://github.com/websockets/ws#broadcast-example

先来看下我的成果:在谷歌和火狐浏览器上链接上websocet实现同步。

客户端1

技术分享

客户端2

技术分享

客户端1

技术分享

 

先贴上我的后台代码(nodejs):

需要安装express模块、ws模块

 1 var express = require(‘express‘);
 2 var http = require(‘http‘);
 3 var WebSocket = require(‘ws‘);
 4 
 5 var app = express();
 6 app.use(express.static(__dirname));
 7 
 8 var server = http.createServer(app);
 9 var wss = new WebSocket.Server({server});
10 
11 wss.on(‘connection‘, function connection(ws) {
12     console.log(‘链接成功!‘);
13     ws.on(‘message‘, function incoming(data) {
14         /**
15          * 把消息发送到所有的客户端
16          * wss.clients获取所有链接的客户端
17          */
18         wss.clients.forEach(function each(client) {
19             client.send(data);
20         });
21     });
22 });
23 
24 server.listen(8000, function listening() {
25     console.log(‘服务器启动成功!‘);
26 });

 

客户端代码:

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport"
 6  content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>在线聊天</title>
 9 </head>
10 <body>
11 <input type="text" onblur="wsServer.onopen(this.value)">
12 <script>
13  var wsServer = new WebSocket(ws://127.0.0.1:8000);
14  wsServer.onopen = function (e) {
15      (typeof e == string) && wsServer.send(e);//向后台发送数据
16  };
17  wsServer.onclose = function (e) {//当链接关闭的时候触发
18 
19  };
20  wsServer.onmessage = function (e) {//后台返回消息的时候触发
21         console.log(e);
22  };
23  wsServer.onerror = function (e) {//错误情况触发
24 
25  }
26 </script>
27 </body>
28 </html>

写的很简单,反正能运行就行。更多内容点击:meetqy

node+ws模块实现websocket