Node.js WebSocket 客户端实例
Posted yamboo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Node.js WebSocket 客户端实例相关的知识,希望对你有一定的参考价值。
Node.js
var ws = require("ws"); var socket = new ws("ws://127.0.0.1:8001); var socket.on("open", function () { if (socket.readyState == 1) { var msg = {}; msg.status = ‘ok‘; socket.send(JSON.stringify(msg)); } }); var socket.on("error", function (err) { console.log("error: ", err); }); var socket.on("close", function () { console.log("close"); }); var socket.on("message", function (e) { var data = JSON.parse(e.data); });
浏览器
var ws = new WebSocket("ws://127.0.0.1:8001"); ws.onopen = function () { console.log("ws connected!"); }; ws.onerror = function (e) { var strErr = ‘‘; for ( var p in e) { strErr += p + "=" + e[p]+" "; } console.log("ws error occured! "+strErr); }; ws.onclose = function (e) { console.log("ws closed! code:["+e.code+"] msg:"+e.reason) }; ws.onmessage = function (e) { var data = JSON.parse(e.data); };