用python实现的websocket代码.pdf

上传人:tbuqq 文档编号:4452099 上传时间:2019-11-10 格式:PDF 页数:10 大小:109.83KB
返回 下载 相关 举报
用python实现的websocket代码.pdf_第1页
第1页 / 共10页
亲,该文档总共10页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

《用python实现的websocket代码.pdf》由会员分享,可在线阅读,更多相关《用python实现的websocket代码.pdf(10页珍藏版)》请在三一文库上搜索。

1、用 python 实现的 websocket代码 ubuntu 下 python2.76 windows Python 2.79, chrome37 firefox35通过 代码是在别人 (cddn有人提问 )基础上改的 , 主要改动了 parsedata和 sendmessage 这 2 个函数 . 改代码参考下面了这段文档. 主要是第 5 条, 发送的数据长度分别是8bit 和 16bit 和 64 bit(即 127, 65535,和 264-1)三种情况 发送和收取是一样的 , 例如 1.长度小于 125时(由于使用 126, 127用作标志位 .) 2. 数据长度在 128-6552

2、5之间时 , Payload 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-fram

3、e message, it would be set to 1 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

4、of the frame. Control frames communicate 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 frame 2.x1: text frame; this frame (and any following) contains text 3.x

5、2: binary frame; this frame (and any following) contains binary data 4.x3 - x7: non-control reserved frames; these are reserved for possible websocket extensions 5.x8: close frame; this frame should end the connection 6.x9: ping frame 7.xA: pong frame 8.xB - xF: control reserved frames 4.Mask (bit 8

6、): this bit determines whether this 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

7、127, the length is actually determined 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 frame

8、s; we know the size of the entire 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 plain copy 1.#

9、coding=utf8 2.#!/usr/bin/python 3. 4. 5.import struct,socket 6.import hashlib 7.import threading,random 8.import time 9.import struct 10.from base64 import b64encode, b64decode 11. 12. 13.connectionlist = 14.g_code_length = 0 15.g_header_length = 0 16. 17. 18.def hex2dec(string_num): 19.return str(i

10、nt(string_num.upper(), 16) 20. 21. 22. 23. 24.def get_datalength(msg): 25.global g_code_length 26.global g_header_length 27. 28.print (len(msg) 29. g_code_length = ord(msg1) 31.if g_code_length = 126: 32.#g_code_length = msg2:4 33.#g_code_length = (ord(msg2)H, str(msg2:4)0 35. g_header_length = 8 36

11、.elif g_code_length = 127: 37.#g_code_length = msg2:10 38. g_code_length = struct.unpack( Q, str(msg2:10)0 39. g_header_length = 14 40.else : 41. g_header_length = 6 42. g_code_length = int(g_code_length) 43.return g_code_length 44. 45.def parse_data(msg): 46.global g_code_length 47. g_code_length =

12、 ord(msg1) 49.if g_code_length = 126: 50. g_code_length = struct.unpack( H, str(msg2:4)0 51. masks = msg4:8 52. data = msg8: 53.elif g_code_length = 127: 54. g_code_length = struct.unpack( Q, str(msg2:10)0 55. masks = msg10:14 56. data = msg14: 57.else : 58. masks = msg2:6 59. data = msg6: 60. 61. 6

13、2. i = 0 63. raw_str = 64. 65. 66.for d in data: 67. raw_str += chr(ord(d) ord(masksi%4) 68. i += 1 69. 70. 71.print (u“总长度是: %d“ % int(g_code_length) 72.return raw_str 73. 74. 75.def sendMessage(message): 76.global connectionlist 77. 78. message_utf_8 = message.encode(utf-8) 79.for connection in co

14、nnectionlist.values(): 80. back_str = 81. back_str.append( x81) 82. data_length = len(message_utf_8) 83. 84. 85.if data_length h, data_length) 90.#back_str.append(chr(data_length 8) 91.#back_str.append(chr(data_length 106. back_str = str(msg) + message_utf_8 #.encode(utf-8) 107.#connection.send(str.

15、encode(str(u“x00%sxFFnn“ % message) #这个 是旧版 108.#print (usend message: + message) 109.if back_str != None and len(back_str) 0: 110.print (back_str) 111. connection.send(back_str) 112. 113. 114.def deleteconnection(item): 115.global connectionlist 116.del connectionlistconnection+item 117. 118. 119.c

16、lass WebSocket(threading.Thread): #继承 Thread 120. 121. 122. GUID = “258EAFA5-E914-47DA-95CA-C5AB0DC85B11“ 123. 124. 125.def _init_(self,conn,index,name,remote, path= “/“ ): 126. threading.Thread._init_(self) #初始化父类 Thread 127. self.conn = conn 128. self.index = index 129. self.name = name 130. self.

17、remote = remote 131. self.path = path 132. self.buffer = “ 133. self.buffer_utf8 = “ 134. self.length_buffer = 0 135.def run(self):#重载 Thread的 run 136.print(Socket%s Start! % self.index) 137. headers = 138. self.handshaken = False 139. 140. 141.while True: 142.if self.handshaken = False: 143.print (

18、Socket%s Start Handshaken with %s! % (self.index,self.rem ote) 144. self.buffer += bytes.decode(self.conn.recv(1024) 145. 146. 147.if self.buffer.find(rnrn) != -1: 148. header, data = self.buffer.split( rnrn, 1) 149.for line in header.split(“rn“)1: 150. key, value = line.split( “: “, 1) 151. headers

19、key = value 152. 153. 154. headers “Location“ = (“ws:/%s%s“ %(headers “Host“, self.path ) 155. key = headers Sec-WebSocket-Key 156. token = b64encode(hashlib.sha1(str.encode(str(key + self.GUID) ).digest() 157. 158. 159. handshake= “HTTP/1.1 101 Switching Protocolsrn“ 160.“Upgrade: websocketrn“ 161.

20、“Connection: Upgradern“ 162.“Sec-WebSocket-Accept: “+bytes.decode(token)+ “rn“ 163.“WebSocket-Origin: “+str(headers “Origin“ )+“rn“ 164.“WebSocket-Location: “+str(headers “Location“)+“rnrn“ 165. 166. 167. self.conn.send(str.encode(str(handshake) 168. self.handshaken = True 169.print (Socket %s Hands

21、haken with %s success! %(self.index, sel f.remote) 170. sendMessage(u Welcome, + self.name + !) 171. self.buffer_utf8 = “ 172. g_code_length = 0 173. 174. 175.else : 176.global g_code_length 177.global g_header_length 178. mm=self.conn.recv(128) 179.if len(mm) 2. 3. 4.WebSocket 5. 6. 7. html, body 8

22、. font: normal 0.9em arial, helvetica; 9. 10. 11. #log 12. width: 440px; 13. height: 200px; 14. border: 1px solid #7F9DB9; 15. overflow: auto; 16. 17. 18. #msg 19. width: 330px; 20. 21. 22. 23. 24. var socket; 25. 26. function init() 27. var host = “ws:/127.0.0.1:12345/“; 28. try 29.socket = new Web

23、Socket(host); 30.socket.onopen = function (msg) 31. log(Connected); 32. ; 33.socket.onmessage = function (msg) 34. log(msg.data); 35. ; 36.socket.onclose = function (msg) 37. log(“Lose Connection!“); 38. ; 39. 40. catch (ex) 41. log(ex); 42. 43. $(“msg“).focus(); 44. 45. 46. function send() 47. var

24、txt, msg; 48.txt = $(“msg“); 49.msg = txt.value; 50. if (!msg) 51. alert(“Message can not be empty“); 52. return; 53. 54.txt.value = “; 55. txt.focus(); 56. try 57. socket.send(msg); 58. catch (ex) 59. log(ex); 60. 61. 62. 63.window.onbeforeunload = function () 64. try 65. socket.send(quit); 66. soc

25、ket.close(); 67.socket = null; 68. 69. catch (ex) 70. log(ex); 71. 72. ; 73. 74. 75. function $(id) 76. return document.getElementById(id); 77. 78. function log(msg) 79. $(“log“).innerHTML += “ “ + msg; 80. 81. function onkey(event) 82. if (event.keyCode = 13) 83. send(); 84. 85. 86. 87. 88. 89. 90. 91. 92.WebSocket 93. 94. 95. 96. 97.发送 98. 99. 100.

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1