node+ws模塊實現websocket


先來吐槽一下,想要找點技術文章真**不容易,全是**復制粘貼,還冒充原創。搜索一個ws實現websocket全是一樣的。一個字都沒變,我能說什么。最后想到搜索ws模塊githup居然前兩頁沒有,也是那些重復的文章,無力吐槽。推薦一個githup上面的https://github.com/websockets/ws#broadcast-example

先來看下我的成果:在谷歌和火狐瀏覽器上鏈接上websocet實現同步。

先貼上我的后台代碼(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>

寫的很簡單,反正能運行就行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM