標籤:關閉 技術分享 his connect message tps 瀏覽器 data blank
先來吐槽一下,想要找點技術文章真tm不容易,全是jb複製粘貼,還冒充原創。搜尋一個ws實現websocket全是一樣的。一個字都沒變,我能說什麼。最後想到搜尋ws模組githup居然前兩頁沒有,也是那些重複的文章,無力吐槽。奉上一個githup上面的(雖然全是英文的,但是絕壁比那些複製粘貼的好)https://github.com/websockets/ws#broadcast-example
先來看下我的成果:在Google和Firefox瀏覽器上連結上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