websocket js 代码样例

时间:2021-10-31 10:13:51

function StartWebSocket(wsUri) {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { console.log("连接成功,现在你可以发送信息啦!"); };
websocket.onclose = function(evt) { websocket.close(); console.log("websocket连接已断开!"); };
websocket.onmessage = function(evt) { console.log('服务端回应:'+ evt.data); };
websocket.onerror = function(evt) { console.log('发生错误:'+ evt.data); };
}

function doSend(message) {
if (typeof websocket==="undefined"){
alert("websocket还没有连接,或者连接失败,请检测");
return false;
}
if (websocket.readyState==3) {
alert("websocket已经关闭,请重新连接");
return false;
}
websocket.send(message);
}
var websocket;
StartWebSocket("ws://123.207.167.163:9010/ajaxchattest");

doSend("hello")