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]+"\n"; } console.log("ws error occured!\n"+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); };
原文地址:https://www.cnblogs.com/yamboo/p/10658328.html
时间: 2024-10-13 05:01:36