1.node.js中ws模塊建立服務端html
// 加載node上websocket模塊 ws; var ws = require("ws"); // 啓動基於websocket的服務器,監聽咱們的客戶端接入進來。 var server = new ws.Server({ host: "127.0.0.1", port: 8081, }); // 監聽接入進來的客戶端事件 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);
二、網頁客戶端建立(使用WebApi --->WebSocket)node
<!DOCTYPE html> <html> <head> <title>skynet websocket example</title> </head> <body> <script> var ws = new WebSocket("ws://localhost:8081"); ws.onopen = function(){ //鏈接成功觸發 alert("open"); }; ws.onmessage = function(){//接收消息觸發 alert("message"); }; ws.onclose = function(){//關閉鏈接觸發 alert("close"); }; ws.onerror = function(){//鏈接失敗觸發 alert("error"); }; </script> </body> </html>