首先下載websocket模塊,命令行輸入
npm install ws
1.node.js中ws模塊創建服務端
// 加載node上websocket模塊 ws;var ws = require("ws");// 啟動基于websocket的服務器,監聽我們的客戶端接入進來。var server = new ws.Server({ host: "127.0.0.1", port: 6080,});// 監聽接入進來的客戶端事件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已經是根據websocket協議解碼開來的原始數據; // websocket底層有數據包的封包協議,所以,絕對不會出現粘包的情況。 // 每解一個數據包,就會觸發一個message事件; // 不會出現粘包的情況,send一次,就會把send的數據獨立封包。 // 如果我們是直接基于TCP,我們要自己實現類似于websocket封包協議就可以完全達到一樣的效果; 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事件,表示的我們監聽錯誤;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模塊創建客戶端
var ws = require("ws");// url ws://127.0.0.1:6080// 創建了一個客戶端的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.網頁客戶端創建(使用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>
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答