版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、用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 Length位设为126, 后面额外使用
2、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 as it is both the fir
3、st 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 communicate WebSocket st
4、ate, 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 any following) conta
5、ins 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 this specific frame us
6、es 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 determined by bits 16 thr
7、ough 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 entire message by the payl
8、oad 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. 5. importstruct,soc
9、ket6. 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.
10、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=msg2:1038. g_code_lengt
11、h=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_length=struct.unpack
12、(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. i+=169. 70. 71. prin
13、t(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. bac
14、k_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.append(chr(data_length8)10
15、0. #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!=Noneandlen(back_str)0:110.
16、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_init_(self,conn,inde
17、x,name,remote,path=/):126. threading.Thread._init_(self)#初始化父类Thread127. self.conn=conn128. self.index=index129. =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
18、)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.buffer.split(rnrn,1)149
19、. 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/1.1101SwitchingProtoc
20、olsrn160. 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=True169. print(Socket%sHand
21、shakenwith%ssuccess!%(self.index,self.remote)170. sendMessage(uWelcome,++!)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. get_datalength(mm)1
22、83. #接受的长度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_uni
23、code=quit:192. print(uSocket%sLogout!%(self.index)193. nowTime=time.strftime(%H:%M:%S,time.localtime(time.time()194. sendMessage(u%s%ssay:%s%(nowTime,self.remote,+Logout)195. deleteconnection(str(self.index)196. self.conn.close()197. break#退出线程198. else:199. #print(uSocket%sGotmsg:%sfrom%s!
24、%(self.index,msg_unicode,self.remote)200. nowTime=time.strftime(u%H:%M:%S,time.localtime(time.time()201. sendMessage(u%s%ssay:%s%(nowTime,self.remote,msg_unicode)202. #重置buffer和bufferlength203. self.buffer_utf8=204. self.buffer=205. g_code_length=0206. self.length_buffer=0207. self.buffer=208. 209.
25、210. classWebSocketServer(object):211. def_init_(self):212. self.socket=None213. defbegin(self):214. print(WebSocketServerStart!)215. self.socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)216. self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)217. self.socket.bind(,12345)
26、218. self.socket.listen(50)219. 220. 221. globalconnectionlist222. 223. 224. i=0225. whileTrue:226. connection,address=self.socket.accept()227. 228. 229. username=address0230. newSocket=WebSocket(connection,i,username,address)231. newSocket.start()#开始线程,执行run函数232. connectionlistconnection+str(i)=co
27、nnection233. i=i+1234. 235. 236. if_name_=_main_:237. server=WebSocketServer()238. server.begin()客户端测试了chrome37, firefox35htmlview plaincopy1. 2. 3. 4. WebSocket5. 6. 7. html,body8. font:normal0.9emarial,helvetica;9. 10. 11. #log12. width:440px;13. height:200px;14. border:1pxsolid#7F9DB9;15. overflow:auto;16. 17. 18. #msg19. width:330px;20. 21. 22. 23. 24. varsocket;25. 26. functioninit()27. varho
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 铜响乐器制作工岗前技术理论考核试卷含答案
- 产后健康宣教乳房护理
- 综合网络搭建实训
- 2025年佛山市高明区教师招聘笔试参考试题及答案解析
- 2025年牙科诊所员工培训协议
- 2025年吴旗县中小学教师招聘笔试备考试题及答案解析
- 2025年秀山土家族苗族自治县中小学教师招聘笔试参考试题及答案解析
- 2025年抚顺市东洲区中小学教师招聘笔试备考试题及答案解析
- (新版)广东省常用非金属材料检测技术培训考核考试(重点)题库300题(含答案)
- 2025年虚拟数字人直播租赁协议
- 间歇充气加压用于静脉血栓栓塞症预防的中国专家共识解读
- 生产副总年终工作总结
- 青岛啤酒经销商协议合同
- 超声窦卵泡计数临床实践与应用
- 入团考试题及答案2025
- 钓鱼场转让合同范本
- 打木架承包合同协议书
- 高中生艾滋病预防教育课件
- 反洗钱系统优化与可疑交易识别
- 2025年高考语文二轮复习:文言文阅读 5类50题强化练习题(含答案解析)
- 生物质热能供暖系统行业深度调研及发展战略咨询报告
评论
0/150
提交评论