折腾了三天,终于把socket server在handshake时的处理给整通了,前端的onopen事件终于响应了!!!
先贴一下关键部分的代码,记录一下:
==========================================================
def getKey(message):
>> num1 = re.findall(r'Sec-WebSocket-Key1: (.*)\n',message)[0]
>> num2 = re.findall(r'Sec-WebSocket-Key2: (.*)\n',message)[0]
>> key = re.findall(r'\r\n\r\n(.*)$',message)[0]
>> num1_num = int("".join(re.findall(r'\d',num1)))
>> num1_space = len(re.findall(r' ',num1))
>> num2_num = int("".join(re.findall(r'\d',num2)))
>> num2_space = len(re.findall(r' ',num2))
>> return "%s%s%s" % (struct.pack('>L',num1_num/num1_space),struct.pack('>L',num2_num/num2_space),key)
def socketItem(con):
>> while True :
>>>> message = con.recv(1024)
>>>> if not message : break
>>>> print message
>>>> key = getKey(message)
>>>> key = hashlib.md5(key).digest()
>>>> msg = '''HTTP/1.1 101 WebSocket Protocol Handshake\r
Upgrade: WebSocket\r
Connection: Upgrade\r
Sec-WebSocket-Origin: http://localhost\r
Sec-WebSocket-Location: ws://localhost:9111/\r
Sec-WebSocket-Protocol: sample\r\n\r
%s'''.strip() % key
>>>> print msg
>>>> con.send(msg)
============================================
几个重要心得:
1) python转化32位整数用 instruct.pack(">L",num);
2) 管你几进制的数据,反正都能直接相加;
3) 百度在这个时候真是没用,还是得靠google去搜国内的网站才给力,鄙视百度一个 凸 — — 凸。
4) 和handshake无关,但也记一笔。server端send数据时,首尾要分别加“\x00”和"\xFF",中间的正文部分要是utf8格式的,s.encode("UTF8")一下。