




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、用Python实现的WebSocket服务器ubuntu下python2.76windows Python 2.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不再是长度的一部分)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
3、 first and last frame.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.Opcode (bits 4-7): these four bits deterimine the type of the frame. Control frames communicate WebSocket stat
4、e, while non-control frames communicate data. The various types of codes include:x0: continuation frame; this frame contains data that should be appended to the previous framex1: text frame; this frame (and any following) contains textx2: binary frame; this frame (and any following) contains binary
5、datax3 - x7: non-control reserved frames; these are reserved for possible websocket extensionsx8: close frame; this frame should end the connectionx9: ping framexA: pong framexB - xF: control reserved framesMask (bit 8): this bit determines whether this specific frame uses a mask or not.Payload Leng
6、th (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, the following
7、eight bytes).Masking Key (the following four bytes): this represents the mask, if the Mask bit is set to 1.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 sent, and can appe
8、nd 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.服务器python view plain copy 在CODE上查看代码片派生到我的代码片#coding=utf8 #!/usr/bin/python import struct,socket import hashlib import thre
9、ading,random import time import struct from base64 import b64encode, b64decode connectionlist = g_code_length = 0 g_header_length = 0 def hex2dec(string_num): return str(int(string_num.upper(), 16) def get_datalength(msg): global g_code_length global g_header_length print (len(msg) g_code_length = o
10、rd(msg1) & 127 received_length = 0; if g_code_length = 126: #g_code_length = msg2:4 #g_code_length = (ord(msg2)H, str(msg2:4)0 g_header_length = 8 elif g_code_length = 127: #g_code_length = msg2:10 g_code_length = struct.unpack(Q, str(msg2:10)0 g_header_length = 14 else: g_header_length = 6 g_code_l
11、ength = int(g_code_length) return g_code_length def parse_data(msg): global g_code_length g_code_length = ord(msg1) & 127 received_length = 0; if g_code_length = 126: g_code_length = struct.unpack(H, str(msg2:4)0 masks = msg4:8 data = msg8: elif g_code_length = 127: g_code_length = struct.unpack(Q,
12、str(msg2:10)0 masks = msg10:14 data = msg14: else: masks = msg2:6 data = msg6: i = 0 raw_str = for d in data: raw_str += chr(ord(d) ord(masksi%4) i += 1 print (u总长度是:%d % int(g_code_length) return raw_str def sendMessage(message): global connectionlist message_utf_8 = message.encode(utf-8) for conne
13、ction in connectionlist.values(): back_str = back_str.append(x81) data_length = len(message_utf_8) if data_length = 125: back_str.append(chr(data_length) elif data_length h, data_length) #back_str.append(chr(data_length 8) #back_str.append(chr(data_length & 0xFF) #a = struct.pack(h, data_length) #b
14、= chr(data_length 8) #c = chr(data_length & 0xFF) elif data_length q, data_length) #back_str.append(chr(data_length 8) #back_str.append(chr(data_length & 0xFF) else : print (u太长了) msg = for c in back_str: msg += c; back_str = str(msg) + message_utf_8#.encode(utf-8) #connection.send(str.encode(str(ux
15、00%sxFFnn % message) #这个是旧版 #print (usend message: + message) if back_str != None and len(back_str) 0: print (back_str) connection.send(back_str) def deleteconnection(item): global connectionlist del connectionlistconnection+item class WebSocket(threading.Thread):#继承Thread GUID = 258EAFA5-E914-47DA-
16、95CA-C5AB0DC85B11 def _init_(self,conn,index,name,remote, path=/): threading.Thread._init_(self)#初始化父类Thread self.conn = conn self.index = index = name self.remote = remote self.path = path self.buffer = self.buffer_utf8 = self.length_buffer = 0 def run(self):#重载Thread的run print(Socket%s S
17、tart! % self.index) headers = self.handshaken = False while True: if self.handshaken = False: print (Socket%s Start Handshaken with %s! % (self.index,self.remote) self.buffer += bytes.decode(self.conn.recv(1024) if self.buffer.find(rnrn) != -1: header, data = self.buffer.split(rnrn, 1) for line in h
18、eader.split(rn)1: key, value = line.split(: , 1) headerskey = value headersLocation = (ws:/%s%s %(headersHost, self.path) key = headersSec-WebSocket-Key token = b64encode(hashlib.sha1(str.encode(str(key + self.GUID).digest() handshake=HTTP/1.1 101 Switching Protocolsrn Upgrade: websocketrn Connectio
19、n: Upgradern Sec-WebSocket-Accept: +bytes.decode(token)+rn WebSocket-Origin: +str(headersOrigin)+rn WebSocket-Location: +str(headersLocation)+rnrn self.conn.send(str.encode(str(handshake) self.handshaken = True print (Socket %s Handshaken with %s success! %(self.index, self.remote) sendMessage(uWelc
20、ome, + + !) self.buffer_utf8 = g_code_length = 0 else: global g_code_length global g_header_length mm=self.conn.recv(128) if len(mm) = 0: continue if g_code_length = 0: get_datalength(mm) #接受的长度 self.length_buffer = self.length_buffer + len(mm) self.buffer = self.buffer + mm if self.length
21、_buffer - g_header_length g_code_length : continue else : self.buffer_utf8 = parse_data(self.buffer) #utf8 msg_unicode = str(self.buffer_utf8).decode(utf-8, ignore) #unicode if msg_unicode=quit: print (uSocket%s Logout! % (self.index) nowTime = time.strftime(%H:%M:%S,time.localtime(time.time() sendM
22、essage(u%s %s say: %s % (nowTime, self.remote, + Logout) deleteconnection(str(self.index) self.conn.close() break #退出线程 else: #print (uSocket%s Got msg:%s from %s! % (self.index, msg_unicode, self.remote) nowTime = time.strftime(u%H:%M:%S,time.localtime(time.time() sendMessage(u%s %s say: %
23、s % (nowTime, self.remote, msg_unicode) #重置buffer和bufferlength self.buffer_utf8 = self.buffer = g_code_length = 0 self.length_buffer = 0 self.buffer = class WebSocketServer(object): def _init_(self): self.socket = None def begin(self): print( WebSocketServer Start!) self.socket = socket.socket(socke
24、t.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) self.socket.bind(,12345) self.socket.listen(50) global connectionlist i=0 while True: connection, address = self.socket.accept() username=address0 newSocket = WebSocket(connection,i,username,addre
25、ss) newSocket.start() #开始线程,执行run函数 connectionlistconnection+str(i)=connection i = i + 1 if _name_ = _main_: server = WebSocketServer() server.begin() 客户端 测试了chrome37, firefox35html view plain copy 在CODE上查看代码片派生到我的代码片 WebSocket html, body font: normal 0.9em arial, helvetica; #log width: 440px; height: 200px; b
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 门诊承包协议合同范本
- 保利华府购房合同范本
- 青少年成长观察课程合同
- 耕地承包出租合同范本
- 安全生产总承包合同
- 员工餐厅服务合同范本
- 整人收费服务合同范本
- 特种空调采购合同范本
- 温控大棚租赁合同范本
- 简易板房销售合同范本
- 锂离子电池正极材料研究进展
- 二手房屋买卖物品交接清单
- 技师论文 变频器的维修与保养
- 非标自动化设备项目进度表
- 诊断学教学胸部查体
- 桥梁安全事故案例警示
- YY/T 1095-2015肌电生物反馈仪
- SB/T 10460-2008商用电开水器
- GB/T 9124.1-2019钢制管法兰第1部分:PN系列
- GA 1800.2-2021电力系统治安反恐防范要求第2部分:火力发电企业
- 欣旺集团种禽养殖管理制度手册
评论
0/150
提交评论