为什么需要 webSocket
- 因为
HTTP 协议有一个缺陷:通信只能由客户端发起; - 如果服务器有连续的状态变化,客户端要获取的话,只能使用 轮询 的方式,非常浪费资源(不停的连接,或者
HTTP 连接始终打开)。
特点
- 服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话;
- 建立在
TCP 协议之上,服务器端的实现比较容易; - 没有同源限制,客户端可以与任意服务器通信;
- 数据格式比较轻量,性能开销小,通信高效。
代码实现(基于 vue)
methods: { //初始化weosocket initWebSocket(){ const wsuri = `ws://192.168.18.169:8059/websocket/${localStorage.getItem('userId')}`//这个地址由后端童鞋提供 this.websock = new WebSocket(wsuri); this.websock.onmessage = this.websocketonmessage; this.websock.onopen = this.websocketonopen; this.websock.onerror = this.websocketonerror; this.websock.onclose = this.websocketclose; }, //连接建立之后执行send方法发送数据 websocketonopen(){ this.websocketsend(this.user) console.log(111); }, //连接建立失败重连 websocketonerror(){ this.initWebSocket() }, // 获取到数据 websocketonmessage(e){ // do something }, // 向服务器推送数据 websocketsend(Data){ this.websock.send(Data) }, // 关闭 websocketclose(e){ console.log('断开连接', e) }}