用Python实现一个简单的WebSocket服务器_第1页
用Python实现一个简单的WebSocket服务器_第2页
用Python实现一个简单的WebSocket服务器_第3页
用Python实现一个简单的WebSocket服务器_第4页
用Python实现一个简单的WebSocket服务器_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、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, 后面额外使用16bit表示长度(前面的126不再是长度

2、的一部分)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 first and last frame.2.

3、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 state, while non-control

4、 frames communicate data. The various types of codes include:4.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) contains binary data4. x3

5、 - 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 frames5. Mask (bit 8): this bit determines whether this specific frame uses a mask or not.6.

6、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 through 79 (that is, th

7、e following eight bytes).7. Masking Key (the following four bytes): this represents the mask, if the Mask bit is set to 1.8. 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 payload length that was

8、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,socket6. importhashlib7.

9、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.

10、 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_length=struct.unpack(Q,str(

11、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(H,str(msg2:4)051. mas

12、ks=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. print(u总长度是:%d%int(g_code_

13、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_

14、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)100. #back_str.append(ch

15、r(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. print(back_str)111. co

16、nnection.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,index,name,remote,path=/):

17、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)137. headers=138. sel

18、f.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. forlineinheader.spli

19、t(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.1101SwitchingProtocolsrn160. Upgrade:webs

20、ocketrn161. 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%sHandshakenwith%ssuccess!%(

21、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)183. #接受的长度184. self.le

22、ngth_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(u

23、Socket%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!%(self.index,msg_unico

24、de,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. 210. classWebSocketSer

25、ver(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)218. self.socket.liste

26、n(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)=connection233. i=i+1234.

27、 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. varhost=

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论