我面臨的任務是爲websocket提供支持,爲Python實現一個簡單的服務器句柄。當然我知道關於tornadoIO,但問題在於實現它。 連接和握手(交換私鑰)的步驟,我做了,但後來我有問題。 1)來自客戶端(瀏覽器)的消息確實出現,但它們被編碼。我找到了關於它的信息,但無法弄清楚如何解碼它們。文檔說消息隱藏在掩碼下面(據我所知它是一個XOR),但是打開這個掩碼的鑰匙沒有被客戶端(瀏覽器)拒絕,或者我沒有看到它。 2)發送服務器的消息,客戶端(瀏覽器)被忽略。根據文檔python.problems上的websocket服務器
conn.send(bytes(0x00))
conn.send(u'test'.encode('utf-8'))
conn.send(bytes(0xFF))
上傳的源代碼here 發送和我這裏
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import socket,sys,hashlib,time
from base64 import b64encode
from threading import Thread
#===================================
bindto=['127.3.1.4',80]
thr_kill=False
def getsett(text,ss,si,es):
#this function i'm use for cut strings by known patterns
global getsett_i1,getsett_i2
if text==None: return None
if ss==None: return None
if es==None: return None
text1=text.lower()
ss=ss.lower()
es=es.lower()
if ss!='': getsett_i1=text1.find(ss,si)
else: getsett_i1=si
if getsett_i1==-1: return None
if es!='': getsett_i2=text1.find(es,getsett_i1+len(ss))
else: getsett_i2=len(text1)
if getsett_i2==-1: return None
return text[getsett_i1+len(ss):getsett_i2]
def thr_waitclient():
global bindto,thr_kill
serv=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serv.bind((bindto[0],bindto[1]))
while thr_kill==False:
serv.listen(1)
conn,adr=serv.accept()
data=conn.recv(4096)
print data
#checking connection type
if getsett(data,'connection: ',0,"\r\n").lower()=='upgrade' and getsett(data,'upgrade: ',0,"\r\n").lower()=='websocket':
#handshake
wbs=getsett(data,'Sec-WebSocket-Key: ',0,"\r\n")
conn.send("HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "+b64encode(hashlib.sha1(wbs+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest())+"\r\nSec-WebSocket-Origin: *\r\nAccess-Control-Allow-Origin: *\r\nOrigin: *\r\nAccess-Control-Allow-Credentials:true\r\nAccess-Control-Allow-Headers:content-type\r\n\r\n")
#wait for clien's messahe,then send response
while True:
print conn.recv(4096) #first problem:message is coded
conn.send(bytes(0x00))
conn.send(u'test'.encode('utf-8'))
conn.send(bytes(0xFF))
#second problem: client ignore message
time.sleep(0.5)
else:
conn.close()
serv.close()
Thread(None,thr_waitclient).start()
while thr_kill!=True:
time.sleep(0.3)
sys.exit(0)
你看現有的實現,如高速公路,ws4py,txws? – jfs 2012-03-10 00:02:56