node.js中ws模塊創(chuàng)建服務端和客戶端,網(wǎng)頁WebSocket客戶端
更新時間:2019年03月06日 10:37:20 作者:jadeshu
今天小編就為大家分享一篇關于node.js中ws模塊創(chuàng)建服務端和客戶端,網(wǎng)頁WebSocket客戶端,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
首先下載websocket模塊,命令行輸入
npm install ws
1.node.js中ws模塊創(chuàng)建服務端
// 加載node上websocket模塊 ws; var ws = require("ws"); // 啟動基于websocket的服務器,監(jiān)聽我們的客戶端接入進來。 var server = new ws.Server({ host: "127.0.0.1", port: 6080, }); // 監(jiān)聽接入進來的客戶端事件 function websocket_add_listener(client_sock) { // close事件 client_sock.on("close", function() { console.log("client close"); }); // error事件 client_sock.on("error", function(err) { console.log("client error", err); }); // end // message 事件, data已經(jīng)是根據(jù)websocket協(xié)議解碼開來的原始數(shù)據(jù); // websocket底層有數(shù)據(jù)包的封包協(xié)議,所以,絕對不會出現(xiàn)粘包的情況。 // 每解一個數(shù)據(jù)包,就會觸發(fā)一個message事件; // 不會出現(xiàn)粘包的情況,send一次,就會把send的數(shù)據(jù)獨立封包。 // 如果我們是直接基于TCP,我們要自己實現(xiàn)類似于websocket封包協(xié)議就可以完全達到一樣的效果; client_sock.on("message", function(data) { console.log(data); client_sock.send("Thank you!"); }); // end } // connection 事件, 有客戶端接入進來; function on_server_client_comming (client_sock) { console.log("client comming"); websocket_add_listener(client_sock); } server.on("connection", on_server_client_comming); // error事件,表示的我們監(jiān)聽錯誤; function on_server_listen_error(err) { } server.on("error", on_server_listen_error); // headers事件, 回給客戶端的字符。 function on_server_headers(data) { // console.log(data); } server.on("headers", on_server_headers);
2.node.js中ws模塊創(chuàng)建客戶端
var ws = require("ws"); // url ws://127.0.0.1:6080 // 創(chuàng)建了一個客戶端的socket,然后讓這個客戶端去連接服務器的socket var sock = new ws("ws://127.0.0.1:6080"); sock.on("open", function () { console.log("connect success !!!!"); sock.send("HelloWorld1"); sock.send("HelloWorld2"); sock.send("HelloWorld3"); sock.send("HelloWorld4"); sock.send(Buffer.alloc(10)); }); sock.on("error", function(err) { console.log("error: ", err); }); sock.on("close", function() { console.log("close"); }); sock.on("message", function(data) { console.log(data); });
3.網(wǎng)頁客戶端創(chuàng)建(使用WebApi --->WebSocket)
<!DOCTYPE html> <html> <head> <title>skynet websocket example</title> </head> <body> <script> var ws = new WebSocket("ws://127.0.0.1:6080/index.html"); ws.onopen = function(){ alert("open"); ws.send("WebSocket hellowrold!!"); }; ws.onmessage = function(ev){ alert(ev.data); }; ws.onclose = function(ev){ alert("close"); }; ws.onerror = function(ev){ console.log(ev); alert("error"); }; </script> </body> </html>
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
Node.js?使用?zlib?內置模塊進行?gzip?壓縮
這篇文章主要介紹了Node.js?使用?zlib?內置模塊進行?gzip?壓縮,nodejs為我們提供了一個zlib內置模塊,我們可以使用它其中的gzip方法來對傳遞的數(shù)據(jù)進行壓縮,從而提高數(shù)據(jù)傳遞效率,更多相關內容需要的朋友可以參考一下2022-09-09從零學習node.js之利用express搭建簡易論壇(七)
這篇文章主要介紹了node.js利用express搭建簡易論壇的方法,我們需要搭建的這個簡易的論壇主要的功能有:注冊、登錄、發(fā)布主題、回復主題。下面我們來一步步地講解這個系統(tǒng)是如何實現(xiàn)的,需要的朋友可以參考借鑒。2017-02-02