WebSocket是一种在Web浏览器和Web服务器之间创建持久性连接的通信协议。它允许客户端和服务器之间进行全双工通信,这意味着服务器可以主动向客户端发送数据,而不需要客户端首先发起请求。通常用于实时数据传输的场景
背景
- 在 websocket 出来前,想实现实时通信、变更推送、服务端信息推送功能,一般方案是使用 ajax 短轮询、长轮询两种方式
- 短轮询(short polling)是客户端定时向服务器发出请求,询问服务器是否有新的数据。如果服务器有新的数据,就立即返回给客户端;如果没有,就返回一个空的响应。这种方式的问题是如果数据变化的频率比较低,会产生大量无效请求,浪费带宽。
- 长轮询(long polling)也是客户端向服务器发出请求,但服务器并不立即返回响应,而是等到有新的数据时才返回。这样就可以减少无效请求,降低带宽的消耗。但长轮询可能导致服务器需要维持大量未完成的请求,增加了服务器的负担。
通信过程以及原理
建立链接
- WebSocket 协议属于应用层协议,依赖传输层的 TCP 协议。通过 HTTP/1.1 协议的101状态码进行握手建立连接
具体过程
- 客户端发送一个 HTTP GET 请求到服务器,请求的路径是 WebSocket 的路径(类似 ws://example.com/socket)。请求中包含一些特殊的头字段,如 Upgrade: websocket 和 Connection: Upgrade,以表明客户端希望升级连接为 WebSocket
- 服务器收到这个请求后,会返回一个 HTTP 101 状态码(协议切换协议)。同样在响应头中包含 Upgrade: websocket 和 Connection: Upgrade,以及一些其他的 WebSocket 特定的头字段,例如 Sec-WebSocket-Accept,用于验证握手的合法性
- 客户端和服务器之间的连接从普通的 HTTP 连接升级为 WebSocket 连接。之后,客户端和服务器之间的通信就变成了 WebSocket 帧的传输,而不再是普通的 HTTP 请求和响应
优缺点
优点
- 实时性
- 减少网络延迟:与短轮询和长轮询相比
- 较小的数据传输开销:WebSocket 的数据帧相比于 HTTP 请求报文较小
- 较低的服务器资源占用
- 跨域通信:与一些其他跨域通信方法相比,WebSocket 更容易实现跨域通信
缺点
- 连接状态保持
- 不适用于所有场景
- 复杂性
适用场景
- 实时聊天应用
- 在线协作和协同编辑
- 实时数据展示
- 在线游戏
- 推送服务