Python通过websocket与js客户端通信示例分析

2019-10-06 14:02:39王振洲

具体的 websocket 介绍可见 http://zh.wikipedia.org/wiki/WebSocket 

这里,介绍如何使用 Python 与前端 js 进行通信。

websocket 使用 HTTP 协议完成握手之后,不通过 HTTP 直接进行 websocket 通信。

于是,使用 websocket 大致两个步骤:使用 HTTP 握手,通信。

js 处理 websocket 要使用 ws 模块; Python 处理则使用 socket 模块建立 TCP 连接即可,比一般的 socket ,只多一个握手以及数据处理的步骤。

握手

过程

包格式

js 客户端先向服务器端 python 发送握手包,格式如下:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

服务器回应包格式:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat

其中, Sec-WebSocket-Key 是随机的,服务器用这些数据构造一个 SHA-1 信息摘要。

方法为: key+migic , SHA-1  加密, base-64 加密,如下:

Python 中的处理代码

MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
res_key = base64.b64encode(hashlib.sha1(sec_key + MAGIC_STRING).digest())

握手完整代码

js 端

js 中有处理 websocket 的类,初始化后自动发送握手包,如下:

var socket = new WebSocket('ws://localhost:3368');

Python 端

Python 用 socket 接受得到握手字符串,处理后发送

HOST = 'localhost'
PORT = 3368
MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
HANDSHAKE_STRING = "HTTP/1.1 101 Switching Protocolsrn" 
      "Upgrade:websocketrn" 
      "Connection: Upgradern" 
      "Sec-WebSocket-Accept: {1}rn" 
      "WebSocket-Location: ws://{2}/chatrn" 
      "WebSocket-Protocol:chatrnrn"
 
def handshake(con):
#con为用socket,accept()得到的socket
#这里省略监听,accept的代码,具体可见blog:http://blog.csdn.net/ice110956/article/details/29830627
 headers = {}
 shake = con.recv(1024)
 
 if not len(shake):
  return False
 
 header, data = shake.split('rnrn', 1)
 for line in header.split('rn')[1:]:
  key, val = line.split(': ', 1)
  headers[key] = val
 
 if 'Sec-WebSocket-Key' not in headers:
  print ('This socket is not websocket, client close.')
  con.close()
  return False
 
 sec_key = headers['Sec-WebSocket-Key']
 res_key = base64.b64encode(hashlib.sha1(sec_key + MAGIC_STRING).digest())
 
 str_handshake = HANDSHAKE_STRING.replace('{1}', res_key).replace('{2}', HOST + ':' + str(PORT))
 print str_handshake
 con.send(str_handshake)
return True