首先下載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,然后讓這個客戶端去連接服務器的socketvar 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>總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對錯新站長站的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
新聞熱點
疑難解答
圖片精選