为什么需要 webSocket

  1. 因为 HTTP 协议有一个缺陷:通信只能由客户端发起;
  2. 如果服务器有连续的状态变化,客户端要获取的话,只能使用 轮询 的方式,非常浪费资源(不停的连接,或者 HTTP 连接始终打开)。

特点

  1. 服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话;
  2. 建立在 TCP 协议之上,服务器端的实现比较容易;
  3. 没有同源限制,客户端可以与任意服务器通信;
  4. 数据格式比较轻量,性能开销小,通信高效。

代码实现(基于 vue)

  1. methods: {
  2. //初始化weosocket
  3. initWebSocket(){
  4. const wsuri = `ws://192.168.18.169:8059/websocket/${localStorage.getItem('userId')}`//这个地址由后端童鞋提供
  5. this.websock = new WebSocket(wsuri);
  6. this.websock.onmessage = this.websocketonmessage;
  7. this.websock.onopen = this.websocketonopen;
  8. this.websock.onerror = this.websocketonerror;
  9. this.websock.onclose = this.websocketclose;
  10. },
  11. //连接建立之后执行send方法发送数据
  12. websocketonopen(){
  13. this.websocketsend(this.user)
  14. console.log(111);
  15. },
  16. //连接建立失败重连
  17. websocketonerror(){
  18. this.initWebSocket()
  19. },
  20. // 获取到数据
  21. websocketonmessage(e){
  22. // do something
  23. },
  24. // 向服务器推送数据
  25. websocketsend(Data){
  26. this.websock.send(Data)
  27. },
  28. // 关闭
  29. websocketclose(e){
  30. console.log('断开连接', e)
  31. }
  32. }