WebSocket即时通讯简单使用方法

1,747 阅读1分钟

第一步 初始化WebSocket对象

http协议时:
that.ws = new WebSocket(`ws://www.test.com/send_message/${id}-${name}`);

https协议时:
that.ws = new WebSocket(`wss://www.test.com/send_message/${id}-${name}`);

第二步 与服务端建立连接触发

that.ws.onopen = function () { console.log("与服务器成功建立连接")};

第三步 服务端推送消息触发

this.ws.onmessage =function (ev) { that.talking(ev.data); } talking(){//处理数据}

第四步 发生错误触发

this.ws.onerror = function () { console.log("连接错误")};

第五步 正常关闭触发

this.ws.onclose = function () { console.log("连接关闭");};

第六步 发送数据

this.ws.send(JSON.stringify(json))

第七步 关闭连接

window.onbeforeunload =  ()=> {    
    that.ws.close();    
    console.log('谢谢光临1');    
    return ('谢谢光临2');//IE 谷歌浏览器提示(opera浏览器只有刷新时提示)
}