Websocket 介绍

发布时间: 更新时间: 总字数:897 阅读时间:2m 作者:IP:上海 网址

WebSocket 是基于 TCP 的网络协议,对应 TCP Socket,可以使用 HTTP(Web)上的 Socket 通信规范。

介绍

  • WebSocket 主要实现双向的实时通信
    • 2011 年 IETF 发布了 WebSocket(RFC 6455)
    • Web + Socket 组成
      • 使用 HTTP 协议通过 握手 过程建立连接,握手时通过 Upgrade: web-socket 头进行协议升级
      • 使用 TCP 的全双工通信协议通信
  • WebSocket 是一个轻量级的协议,兼容 TCP 和 HTTP 的优点
    • 头部小,解决带宽资源
    • 使用二进制帧传输数据
    • 支持数据压缩
    • 有状态的持久连接
    • 全双工通信,支持实时数据交换
  • 访问
    • ws:// 基于 HTTP 协议
    • wss:// 基于 HTTPs 协议
  • 一般使用
    • 客户端发送一个字符串(如 json),服务端收到后响应对应的结果,反之亦可

客户端

websocat

# 安装
wget -O websocat https://github.com/vi/websocat/releases/download/v1.9.0/websocat_linux64
chmod 755 websocat
mv websocat /usr/bin/

# 使用
websocat ws://<url>

demo

golang 实现

gorilla/websocket example ...

Socket.IO

F&Q

the client is not using the websocket protocol: ‘upgrade’ token not found in ‘Connection’ header

源码,解决方式,通过 nginx 代理,配置如下

location /ws/ {
	proxy_set_header   X-Forwarded-For $remote_addr;
	proxy_set_header   Host $http_host;
	proxy_set_header   Upgrade websocket;
	proxy_set_header   Connection Upgrade;
	proxy_pass         "http://127.0.0.1:1323";
}

websocket: unsupported version: 13 not found in ‘Sec-Websocket-Version’ header

  • 源码
  • Sec-WebSocket-Key 是 WebSocket 客户端发送的一个 base64 编码的密文,要求服务端必须返回一个对应加密的 Sec-WebSocket-Accept 应答
  • Sec-WebSocket-Version 是版本为 13,上面两个参数理论上会自己带上,也可以通过 Nginx 配置?
proxy_set_header Sec-WebSocket-Key sN9cRrP/n9NdMgdcy2VJFQ==
proxy_set_header Sec-WebSocket-Version 13

扩展

本文总阅读量 次 本站总访问量 次 本站总访客数