1. 程式人生 > >node+ws模塊實現websocket

node+ws模塊實現websocket

ctype name ket 不容易 max 客戶端代碼 tps nod target

先來吐槽一下,想要找點技術文章真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