用python實(shí)現(xiàn)的websocket代碼_第1頁
用python實(shí)現(xiàn)的websocket代碼_第2頁
用python實(shí)現(xiàn)的websocket代碼_第3頁
用python實(shí)現(xiàn)的websocket代碼_第4頁
用python實(shí)現(xiàn)的websocket代碼_第5頁
已閱讀5頁,還剩5頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、用python實(shí)現(xiàn)的websocket代碼ubuntu下python2.76windowsPython2.79, chrome37 firefox35通過代碼是在別人(cddn有人提問)基礎(chǔ)上改的, 主要改動(dòng)了parsedata和sendmessage這2個(gè)函數(shù).改代碼參考下面了這段文檔. 主要是第5條, 發(fā)送的數(shù)據(jù)長度分別是 8bit和 16bit和 64 bit(即127, 65535,和264-1)三種情況發(fā)送和收取是一樣的, 例如1.長度小于125時(shí)(由于使用126, 127用作標(biāo)志位.)2. 數(shù)據(jù)長度在128-65525之間時(shí),Payload Length位設(shè)為126, 后面額外使用

2、16bit表示長度(前面的126不再是長度的一部分)3.數(shù)據(jù)長度在65526-264-1之間時(shí),Payload Length位設(shè)為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)#這個(gè)是舊版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()#開始線程,執(zhí)行run函數(shù)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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論