1、用python实现的websocket代码用python实现的websocket代码ubuntu下python2.76windowsPython2.79, chrome37 firefox35通过代码是在别人(cddn有人提问)基础上改的, 主要改动了parsedata和sendmessage这2个函数.改代码参考下面了这段文档. 主要是第5条, 发送的数据长度分别是 8bit和 16bit和 64 bit(即127, 65535,和264-1)三种情况发送和收取是一样的, 例如1.长度小于125时(由于使用126, 127用作标志位.)2. 数据长度在128-65525之间时,Payload
2、 Length位设为126, 后面额外使用16bit表示长度(前面的126不再是长度的一部分)3.数据长度在65526-264-1之间时,Payload Length位设为127, 后面额外使用64bit表示长度(前面的127不再是长度的一部分)1. Fin (bit 0): determines if this is the last frame in the message. This would be set to 1 on the end of a series of frames, or in a single-frame message, it would be set to 1
3、as it is both the first and last frame.2. RSV1, RSV2, RSV3 (bits 1-3): these three bits are reserved for websocket extensions, and should be 0 unless a specific extension requires the use of any of these bytes.3. Opcode (bits 4-7): these four bits deterimine the type of the frame. Control frames com
4、municate WebSocket state, while non-control frames communicate data. The various types of codes include:1. x0: continuation frame; this frame contains data that should be appended to the previous frame2. x1: text frame; this frame (and any following) contains text3. x2: binary frame; this frame (and
5、 any following) contains binary data4. x3 - x7: non-control reserved frames; these are reserved for possible websocket extensions5. x8: close frame; this frame should end the connection6. x9: ping frame7. xA: pong frame8. xB - xF: control reserved frames4. Mask (bit 8): this bit determines whether t
6、his specific frame uses a mask or not.5. Payload Length (bits 9-15, or 16-31, or 16-79): these seven bytes determine the payload length. If the length is 126, the length is actually determined by bits 16 through 31 (that is, the following two bytes). If the length is 127, the length is actually dete
7、rmined by bits 16 through 79 (that is, the following eight bytes).6. Masking Key (the following four bytes): this represents the mask, if the Mask bit is set to 1.7. Payload Data (the following data): finally, the data. The payload data may be sent over multiple frames; we know the size of the entir
8、e message by the payload length that was sent, and can append data together to form a single message until we receive the message with the Fin flag. Each consecutive payload, if it exists, will contain the 0 “continuation frame” opcode.具体代码:pythonview plaincopy1. #coding=utf82. #!/usr/bin/python3. 4
9、. 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
10、_datalength(msg):25. globalg_code_length26. globalg_header_length27. 28. print(len(msg)29. g_code_length=ord(msg1)&12730. received_length=0;31. ifg_code_length=126:32. #g_code_length=msg2:433. #g_code_length=(ord(msg2)H,str(msg2:4)035. g_header_length=836. elifg_code_length=127:37. #g_code_length=ms
11、g2:1038. g_code_length=struct.unpack(Q,str(msg2:10)039. 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(msg1)&12748. received_length=0;49. ifg_code_length=126:50. g_code
12、_length=struct.unpack(H,str(msg2:4)051. masks=msg4:852. data=msg8:53. elifg_code_length=127:54. g_code_length=struct.unpack(Q,str(msg2:10)055. masks=msg10:1456. data=msg14:57. else:58. masks=msg2:659. data=msg6:60. 61. 62. i=063. raw_str=64. 65. 66. fordindata:67. raw_str+=chr(ord(d)ord(masksi%4)68.
13、 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. ifda
14、ta_length=125:86. back_str.append(chr(data_length)87. elifdata_lengthh,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_lengthq,data_length)99. #back_str.appen
15、d(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(ux00%sxFFnn%message)#这个是旧版108. #print(usendmessage:+message)109. ifback_str!=Nonean
16、dlen(back_str)0:110. print(back_str)111. connection.send(back_str)112. 113. 114. defdeleteconnection(item):115. globalconnectionlist116. delconnectionlistconnection+item117. 118. 119. classWebSocket(threading.Thread):#继承Thread120. 121. 122. GUID=258EAFA5-E914-47DA-95CA-C5AB0DC85B11123. 124. 125. def
17、_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(Sock
18、et%sStart!%self.index)137. headers=138. self.handshaken=False139. 140. 141. whileTrue:142. ifself.handshaken=False:143. print(Socket%sStartHandshakenwith%s!%(self.index,self.remote)144. self.buffer+=bytes.decode(self.conn.recv(1024)145. 146. 147. ifself.buffer.find(rnrn)!=-1:148. header,data=self.bu
19、ffer.split(rnrn,1)149. forlineinheader.split(rn)1:150. key,value=line.split(:,1)151. headerskey=value152. 153. 154. headersLocation=(ws:/%s%s%(headersHost,self.path)155. key=headersSec-WebSocket-Key156. token=b64encode(hashlib.sha1(str.encode(str(key+self.GUID).digest()157. 158. 159. handshake=HTTP/
20、1.1101SwitchingProtocolsrn160. Upgrade:websocketrn161. Connection:Upgradern162. Sec-WebSocket-Accept:+bytes.decode(token)+rn163. WebSocket-Origin:+str(headersOrigin)+rn164. WebSocket-Location:+str(headersLocation)+rnrn165. 166. 167. self.conn.send(str.encode(str(handshake)168. self.handshaken=True16
21、9. print(Socket%sHandshakenwith%ssuccess!%(self.index,self.remote)170. sendMessage(uWelcome,+self.name+!)171. self.buffer_utf8=172. g_code_length=0173. 174. 175. else:176. globalg_code_length177. globalg_header_length178. mm=self.conn.recv(128)179. iflen(mm)=0:180. continue181. ifg_code_length=0:182
22、. get_datalength(mm)183. #接受的长度184. self.length_buffer=self.length_buffer+len(mm)185. self.buffer=self.buffer+mm186. ifself.length_buffer-g_header_lengthg_code_length:187. continue188. else:189. self.buffer_utf8=parse_data(self.buffer)#utf8190. msg_unicode=str(self.buffer_utf8).decode(utf-8,ignore)#unicode191. ifmsg_unicode=quit:192. print(uSocket%sLogout!%(self.index)193. nowTime=time.strftime(%H:%M:%S,time.localtime(time.time()194. se
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1