您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 销售管理 > 用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不再是长度的一部分)1.Fin(bit0):determinesifthisisthelastframeinthemessage.Thiswouldbesetto1ontheendofaseriesofframes,orinasingle-framemessage,itwouldbesetto1asitisboththefirstandlastframe.2.RSV1,RSV2,RSV3(bits1-3):thesethreebitsarereservedforwebsocketextensions,andshouldbe0unlessaspecificextensionrequirestheuseofanyofthesebytes.3.Opcode(bits4-7):thesefourbitsdeteriminethetypeoftheframe.ControlframescommunicateWebSocketstate,whilenon-controlframescommunicatedata.Thevarioustypesofcodesinclude:4.1.x0:continuationframe;thisframecontainsdatathatshouldbeappendedtothepreviousframe2.x1:textframe;thisframe(andanyfollowing)containstext3.x2:binaryframe;thisframe(andanyfollowing)containsbinarydata4.x3-x7:non-controlreservedframes;thesearereservedforpossiblewebsocketextensions5.x8:closeframe;thisframeshouldendtheconnection6.x9:pingframe7.xA:pongframe8.xB-xF:controlreservedframes5.Mask(bit8):thisbitdetermineswhetherthisspecificframeusesamaskornot.6.PayloadLength(bits9-15,or16-31,or16-79):thesesevenbytesdeterminethepayloadlength.Ifthelengthis126,thelengthisactuallydeterminedbybits16through31(thatis,thefollowingtwobytes).Ifthelengthis127,thelengthisactuallydeterminedbybits16through79(thatis,thefollowingeightbytes).7.MaskingKey(thefollowingfourbytes):thisrepresentsthemask,iftheMaskbitissetto1.8.PayloadData(thefollowingdata):finally,thedata.Thepayloaddatamaybesentovermultipleframes;weknowthesizeoftheentiremessagebythepayloadlengththatwassent,andcanappenddatatogethertoformasinglemessageuntilwereceivethemessagewiththeFinflag.Eachconsecutivepayload,ifitexists,willcontainthe0“continuationframe”opcode.服务器[python]viewplaincopy1.#coding=utf82.#!/usr/bin/python3.4.5.importstruct,socket6.importhashlib7.importthreading,random8.importtime9.importstruct10.frombase64importb64encode,b64decode11.12.13.connectionlist={}14.g_code_length=015.g_header_length=016.17.18.defhex2dec(string_num):19.returnstr(int(string_num.upper(),16))20.21.22.23.24.defget_datalength(msg):25.globalg_code_length26.globalg_header_length27.28.print(len(msg))29.g_code_length=ord(msg[1])&12730.received_length=0;31.ifg_code_length==126:32.#g_code_length=msg[2:4]33.#g_code_length=(ord(msg[2])8)+(ord(msg[3]))34.g_code_length=struct.unpack('H',str(msg[2:4]))[0]35.g_header_length=836.elifg_code_length==127:37.#g_code_length=msg[2:10]38.g_code_length=struct.unpack('Q',str(msg[2:10]))[0]39.g_header_length=1440.else:41.g_header_length=642.g_code_length=int(g_code_length)43.returng_code_length44.45.defparse_data(msg):46.globalg_code_length47.g_code_length=ord(msg[1])&12748.received_length=0;49.ifg_code_length==126:50.g_code_length=struct.unpack('H',str(msg[2:4]))[0]51.masks=msg[4:8]52.data=msg[8:]53.elifg_code_length==127:54.g_code_length=struct.unpack('Q',str(msg[2:10]))[0]55.masks=msg[10:14]56.data=msg[14:]57.else:58.masks=msg[2:6]59.data=msg[6:]60.61.62.i=063.raw_str=''64.65.66.fordindata:67.raw_str+=chr(ord(d)^ord(masks[i%4]))68.i+=169.70.71.print(u总长度是:%d%int(g_code_length))72.returnraw_str73.74.75.defsendMessage(message):76.globalconnectionlist77.78.message_utf_8=message.encode('utf-8')79.forconnectioninconnectionlist.values():80.back_str=[]81.back_str.append('\x81')82.data_length=len(message_utf_8)83.84.85.ifdata_length=125:86.back_str.append(chr(data_length))87.elifdata_length=65535:88.back_str.append(struct.pack('b',126))89.back_str.append(struct.pack('h',data_length))90.#back_str.append(chr(data_length8))91.#back_str.append(chr(data_length&0xFF))92.#a=struct.pack('h',data_length)93.#b=chr(data_length8)94.#c=chr(data_length&0xFF)95.elifdata_length=(2^64-1):96.#back_str.append(chr(127))97.back_str.append(struct.pack('b',127))98.back_str.append(struct.pack('q',data_length))99.#back_str.append(chr(data_length8))100.#back_str.append(chr(data_length&0xFF))101.else:102.print(u'太长了')103.msg=''104.forcinback_str:105.msg+=c;106.back_str=str(msg)+message_utf_8#.encode('utf-8')107.#connection.send(str.encode(str(u\x00%s\xFF\n\n%message)))#这个是旧版108.#print(u'sendmessage:'+message)109.ifback_str!=Noneandlen(back_str)0:110.print(back_str)111.connection.send(back_str)112.113.114.defdeleteconnection(item):115.globalconnectionlist116.delconnectionlist['connection'+item]117.118.119.classWebSocket(threading.Thread):#继承Thread120.121.122.GUID=258EAFA5-E914-47DA-95CA-C5AB0DC85B11123.124.125.def__init__(self,conn,index,name,remote,path=/):126.threading.Thread.__init__(self)#初始化父类Thread127.self.conn=conn128.self.index=index129.self.name=name130.self.remote=remote131.self.path=path132.self.buffer=133.self.buffer_utf8=134.self.length_buffer=0135.defrun(self):#重载Thread的run136.print('Socket%sStart!'%self.index)137.headers={}138.self.handsh
本文标题:用Python实现一个简单的WebSocket服务器
链接地址:https://www.777doc.com/doc-2202545 .html