兼容性:
https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket
一个简单的 Demo
(视频详见原文)
客户端可以在控制台 -network-ws下看到 WebSocket 消息
注意请求头里的几个关键字段
下面以一个实际项目为例,展示如何实现一个WebSocket接口,包含开发->联调->部署→上线整个流程。
将上面的 Demo简单封装一下,在项目中调用如下:
配置 webpack 代理
说明:
为了保证连接稳定,需要考虑一些异常情况,如网络波动导致连接中断,服务器超时等。
心跳检测即客户端定时向服务端发送心跳消息,保持连接稳定;
断线重连即发送消息前,检测连接状态,若连接中断,尝试n次连接;
封装如下:
也可选择第三方库处理。
The WebSocket protocol is different from the HTTP protocol, but the WebSocket handshake is compatible with HTTP, using the HTTP Upgrade facility to upgrade the connection from HTTP to WebSocket.
This allows WebSocket applications to more easily fit into existing infrastructures.
For example, WebSocket applications can use the standard HTTP ports?80 and?443, thus allowing the use of existing firewall rules.
location /websocket {
proxy_pass http://xx.xxx.xx.xx; # websocket服务器。不用管 ws://
proxy_http_version 1.1; # http协议切换
proxy_set_header Host $host; # 保留源信息
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade; # 请求协议升级,如果生产环境有报400错误,可以尝试将值设置为websocket
proxy_set_header Connection $connection_upgrade;
}
sockiet.io是基于 Node 的实时应用程序框架,对比原生 WebSocket,封装了更多通用能力,且在不支持WebSocket的浏览器上,可以降级为轮询方式通信。
优点:成熟,开箱即用,兼容性好。
缺点:体积较大,前后端必须统一,即后端使用?socket.io?则前端必须使用socket.io-client 对应。
作者:vivo 商业化大前端团队
原文:https://blog.51cto.com/14291117/2551605