您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 项目/工程管理 > 用python实现的websocket代码
用python实现的websocket代码ubuntu下python2.76windowsPython2.79,chrome37firefox35通过代码是在别人(cddn有人提问)基础上改的,主要改动了parsedata和sendmessage这2个函数.改代码参考下面了这段文档.主要是第5条,发送的数据长度分别是8bit和16bit和64bit(即127,65535,和2^64-1)三种情况发送和收取是一样的,例如1.长度小于125时(由于使用126,127用作标志位.)2.数据长度在128-65525之间时,PayloadLength位设为126,后面额外使用16bit表示长度(前面的126不再是长度的一部分)3.数据长度在65526-2^64-1之间时,PayloadLength位设为127,后面额外使用64bit表示长度(前面的127不再是长度的一部分)Fin(bit0):determinesifthisisthelastframeinthemessage.Thiswouldbesetto1ontheendofaseriesofframes,orinasingle-framemessage,itwouldbesetto1asitisboththefirstandlastframe.RSV1,RSV2,RSV3(bits1-3):thesethreebitsarereservedforwebsocketextensions,andshouldbe0unlessaspecificextensionrequirestheuseofanyofthesebytes.Opcode(bits4-7):thesefourbitsdeteriminethetypeoftheframe.ControlframescommunicateWebSocketstate,whilenon-controlframescommunicatedata.Thevarioustypesofcodesinclude:x0:continuationframe;thisframecontainsdatathatshouldbeappendedtothepreviousframex1:textframe;thisframe(andanyfollowing)containstextx2:binaryframe;thisframe(andanyfollowing)containsbinarydatax3-x7:non-controlreservedframes;thesearereservedforpossiblewebsocketextensionsx8:closeframe;thisframeshouldendtheconnectionx9:pingframexA:pongframexB-xF:controlreservedframesMask(bit8):thisbitdetermineswhetherthisspecificframeusesamaskornot.PayloadLength(bits9-15,or16-31,or16-79):thesesevenbytesdeterminethepayloadlength.Ifthelengthis126,thelengthisactuallydeterminedbybits16through31(thatis,thefollowingtwobytes).Ifthelengthis127,thelengthisactuallydeterminedbybits16through79(thatis,thefollowingeightbytes).MaskingKey(thefollowingfourbytes):thisrepresentsthemask,iftheMaskbitissetto1.PayloadData(thefollowingdata):finally,thedata.Thepayloaddatamaybesentovermultipleframes;weknowthesizeoftheentiremessagebythepayloadlengththatwassent,andcanappenddatatogethertoformasinglemessageuntilwereceivethemessagewiththeFinflag.Eachconsecutivepayload,ifitexists,willcontainthe0“continuationframe”opcode.服务端代码:#coding=utf8#!/usr/bin/pythonimportstruct,socketimporthashlibimportthreading,randomimporttimeimportstructfrombase64importb64encode,b64decodeconnectionlist={}g_code_length=0g_header_length=0defhex2dec(string_num):returnstr(int(string_num.upper(),16))defget_datalength(msg):globalg_code_lengthglobalg_header_lengthprint(len(msg))g_code_length=ord(msg[1])&127received_length=0;ifg_code_length==126:#g_code_length=msg[2:4]#g_code_length=(ord(msg[2])8)+(ord(msg[3]))g_code_length=struct.unpack('H',str(msg[2:4]))[0]g_header_length=8elifg_code_length==127:#g_code_length=msg[2:10]g_code_length=struct.unpack('Q',str(msg[2:10]))[0]g_header_length=14else:g_header_length=6g_code_length=int(g_code_length)returng_code_lengthdefparse_data(msg):globalg_code_lengthg_code_length=ord(msg[1])&127received_length=0;ifg_code_length==126:g_code_length=struct.unpack('H',str(msg[2:4]))[0]masks=msg[4:8]data=msg[8:]elifg_code_length==127:g_code_length=struct.unpack('Q',str(msg[2:10]))[0]masks=msg[10:14]data=msg[14:]else:masks=msg[2:6]data=msg[6:]i=0raw_str=''fordindata:raw_str+=chr(ord(d)^ord(masks[i%4]))i+=1print(u总长度是:%d%int(g_code_length))returnraw_strdefsendMessage(message):globalconnectionlistmessage_utf_8=message.encode('utf-8')forconnectioninconnectionlist.values():back_str=[]back_str.append('\x81')data_length=len(message_utf_8)ifdata_length=125:back_str.append(chr(data_length))elifdata_length=65535:back_str.append(struct.pack('b',126))back_str.append(struct.pack('h',data_length))#back_str.append(chr(data_length8))#back_str.append(chr(data_length&0xFF))#a=struct.pack('h',data_length)#b=chr(data_length8)#c=chr(data_length&0xFF)elifdata_length=(2^64-1):#back_str.append(chr(127))back_str.append(struct.pack('b',127))back_str.append(struct.pack('q',data_length))#back_str.append(chr(data_length8))#back_str.append(chr(data_length&0xFF))else:print(u'太长了')msg=''forcinback_str:msg+=c;back_str=str(msg)+message_utf_8#.encode('utf-8')#connection.send(str.encode(str(u\x00%s\xFF\n\n%message)))#这个是旧版#print(u'sendmessage:'+message)ifback_str!=Noneandlen(back_str)0:print(back_str)connection.send(back_str)defdeleteconnection(item):globalconnectionlistdelconnectionlist['connection'+item]classWebSocket(threading.Thread):#继承ThreadGUID=258EAFA5-E914-47DA-95CA-C5AB0DC85B11def__init__(self,conn,index,name,remote,path=/):threading.Thread.__init__(self)#初始化父类Threadself.conn=connself.index=indexself.name=nameself.remote=remoteself.path=pathself.buffer=self.buffer_utf8=self.length_buffer=0defrun(self):#重载Thread的runprint('Socket%sStart!'%self.index)headers={}self.handshaken=FalsewhileTrue:ifself.handshaken==False:print('Socket%sStartHandshakenwith%s!'%(self.index,self.remote))self.buffer+=bytes.decode(self.conn.recv(1024))ifself.buffer.find('\r\n\r\n')!=-1:header,data=self.buffer.split('\r\n\r\n',1)forlineinheader.split(\r\n)[1:]:key,value=line.split(:,1)headers[key]=valueheaders[Location]=(ws://%s%s%(headers[Host],self.path))key=headers['Sec-WebSocket-Key']token=b64encode(hashlib.sha1(str.encode(str(key+self.GUID))).digest())handsha
本文标题:用python实现的websocket代码
链接地址:https://www.777doc.com/doc-4583617 .html