python 版websocket实现

简介: ubuntu下python2.76 windows python 2.79, chrome37 firefox35通过 代码是在别人(cddn有人提问)基础上改的, 主要改动了parsedata和sendmessage这2个函数.

ubuntu下python2.76

windows python 2.79, chrome37 firefox35通过

代码是在别人(cddn有人提问)基础上改的, 主要改动了parsedata和sendmessage这2个函数.

改代码参考下面了这段文档. 主要是第5条, 发送的数据长度分别是 8bit和 16bit和 64 bit(即 127, 65535,和2^64-1)三种情况 

发送和收取是一样的, 例如

1.长度小于125时(由于使用126, 127用作标志位.)

2. 数据长度在128-65525之间时, Payload Length位设为126, 后面额外使用16bit表示长度(前面的126不再是长度的一部分)

3.数据长度在65526-2^64-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. 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 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. x2: 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): 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 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 frames; 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.

 

 

 

服务器

 

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. #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(int(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(msg[1]) & 127  
  30.     received_length = 0;  
  31.     if g_code_length == 126:  
  32.         #g_code_length = msg[2:4]  
  33.         #g_code_length = (ord(msg[2])<<8) + (ord(msg[3]))  
  34.         g_code_length = struct.unpack('>H', str(msg[2:4]))[0]  
  35.         g_header_length = 8  
  36.     elif g_code_length == 127:  
  37.         #g_code_length = msg[2:10]  
  38.         g_code_length = struct.unpack('>Q', str(msg[2: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 = ord(msg[1]) & 127  
  48.     received_length = 0;  
  49.     if g_code_length == 126:  
  50.         g_code_length = struct.unpack('>H', str(msg[2:4]))[0]  
  51.         masks = msg[4:8]  
  52.         data = msg[8:]  
  53.     elif g_code_length == 127:  
  54.         g_code_length = struct.unpack('>Q', str(msg[2:10]))[0]  
  55.         masks = msg[10:14]  
  56.         data = msg[14:]  
  57.     else:  
  58.         masks = msg[2:6]  
  59.         data = msg[6:]  
  60.   
  61.   
  62.     i = 0  
  63.     raw_str = ''  
  64.   
  65.   
  66.     for d in data:  
  67.         raw_str += chr(ord(d) ^ ord(masks[i%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 connectionlist.values():  
  80.         back_str = []  
  81.         back_str.append('\x81')  
  82.         data_length = len(message_utf_8)  
  83.   
  84.   
  85.         if data_length <= 125:  
  86.             back_str.append(chr(data_length))  
  87.         elif data_length <= 65535 :  
  88.             back_str.append(struct.pack('b', 126))  
  89.             back_str.append(struct.pack('>h', data_length))  
  90.             #back_str.append(chr(data_length >> 8))  
  91.             #back_str.append(chr(data_length & 0xFF))  
  92.             #a = struct.pack('>h', data_length)  
  93.             #b = chr(data_length >> 8)  
  94.             #c = chr(data_length & 0xFF)  
  95.         elif data_length <= (2^64-1):  
  96.             #back_str.append(chr(127))  
  97.             back_str.append(struct.pack('b', 127))  
  98.             back_str.append(struct.pack('>q', data_length))  
  99.             #back_str.append(chr(data_length >> 8))  
  100.             #back_str.append(chr(data_length & 0xFF))        
  101.         else :  
  102.                 print (u'太长了')          
  103.         msg = ''  
  104.         for c in back_str:  
  105.             msg += c;  
  106.         back_str = str(msg)   + message_utf_8#.encode('utf-8')      
  107.         #connection.send(str.encode(str(u"\x00%s\xFF\n\n" % message))) #这个是旧版  
  108.         #print (u'send 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 connectionlist['connection'+item]  
  117.   
  118.   
  119. class 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.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 ('Socket%s Start Handshaken with %s!' % (self.index,self.remote))  
  144.                 self.buffer += bytes.decode(self.conn.recv(1024))  
  145.   
  146.   
  147.                 if self.buffer.find('\r\n\r\n') != -1:  
  148.                     header, data = self.buffer.split('\r\n\r\n', 1)  
  149.                     for line in header.split("\r\n")[1:]:  
  150.                         key, value = line.split(": ", 1)  
  151.                         headers[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 Protocols\r\n"\  
  160.                         "Upgrade: websocket\r\n"\  
  161.                         "Connection: Upgrade\r\n"\  
  162.                         "Sec-WebSocket-Accept: "+bytes.decode(token)+"\r\n"\  
  163.                         "WebSocket-Origin: "+str(headers["Origin"])+"\r\n"\  
  164.                         "WebSocket-Location: "+str(headers["Location"])+"\r\n\r\n"  
  165.   
  166.   
  167.                     self.conn.send(str.encode(str(handshake)))  
  168.                     self.handshaken = True    
  169.                     print ('Socket %s Handshaken with %s success!' %(self.index, self.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) <= 0:  
  180.                     continue  
  181.                 if g_code_length == 0:  
  182.                     get_datalength(mm)  
  183.                 #接受的长度  
  184.                 self.length_buffer = self.length_buffer + len(mm)  
  185.                 self.buffer = self.buffer + mm  
  186.                 if self.length_buffer - g_header_length < g_code_length :  
  187.                     continue  
  188.                 else :  
  189.                     self.buffer_utf8 = parse_data(self.buffer) #utf8                  
  190.                     msg_unicode = str(self.buffer_utf8).decode('utf-8', 'ignore') #unicode  
  191.                     if msg_unicode=='quit':  
  192.                         print (u'Socket%s Logout!' % (self.index))  
  193.                         nowTime = time.strftime('%H:%M:%S',time.localtime(time.time()))  
  194.                         sendMessage(u'%s %s say: %s' % (nowTime, self.remote, self.name+' Logout'))                        
  195.                         deleteconnection(str(self.index))  
  196.                         self.conn.close()  
  197.                         break #退出线程  
  198.                     else:  
  199.                         #print (u'Socket%s Got msg:%s from %s!' % (self.index, msg_unicode, self.remote))  
  200.                         nowTime = time.strftime(u'%H:%M:%S',time.localtime(time.time()))  
  201.                         sendMessage(u'%s %s say: %s' % (nowTime, self.remote, msg_unicode))    
  202.                     #重置buffer和bufferlength  
  203.                     self.buffer_utf8 = ""  
  204.                     self.buffer = ""  
  205.                     g_code_length = 0  
  206.                     self.length_buffer = 0  
  207.             self.buffer = ""  
  208.   
  209.   
  210. class WebSocketServer(object):  
  211.     def __init__(self):  
  212.         self.socket = None  
  213.     def begin(self):  
  214.         print( 'WebSocketServer Start!')  
  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(("127.0.0.1",12345))  
  218.         self.socket.listen(50)  
  219.   
  220.   
  221.         global connectionlist  
  222.   
  223.   
  224.         i=0  
  225.         while True:  
  226.             connection, address = self.socket.accept()  
  227.   
  228.   
  229.             username=address[0]       
  230.             newSocket = WebSocket(connection,i,username,address)  
  231.             newSocket.start() #开始线程,执行run函数  
  232.             connectionlist['connection'+str(i)]=connection  
  233.             i = i + 1  
  234.   
  235.   
  236. if __name__ == "__main__":  
  237.     server = WebSocketServer()  
  238.     server.begin()  


客户端 

 

测试了chrome37, firefox35

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>WebSocket</title>  
  5.   
  6.     <style>  
  7.         html, body {  
  8.             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.     </style>  
  22.   
  23.     <script>  
  24.         var socket;  
  25.   
  26.         function init() {  
  27.             var host = "ws://127.0.0.1:12345/";  
  28.             try {  
  29.                 socket = new WebSocket(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 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.                 socket.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 += "<br>" + msg;  
  80.         }  
  81.         function onkey(event) {  
  82.             if (event.keyCode == 13) {  
  83.                 send();  
  84.             }  
  85.         }  
  86.     </script>  
  87.   
  88. </head>  
  89.   
  90.   
  91. <body onload="init()">  
  92. <h3>WebSocket</h3>  
  93. <br><br>  
  94.   
  95. <div id="log"></div>  
  96. <input id="msg" type="textbox" onkeypress="onkey(event)"/>  
  97. <button onclick="send()">发送</button>  
  98. </body>  
  99.   
  100. </html>  


参考:用Python实现一个简单的WebSocket服务器

 

 

由于使用125, 126, 127用作标志位.
目录
相关文章
|
3月前
|
前端开发 JavaScript 网络协议
深入理解Python Web开发中的前后端分离与WebSocket实时通信技术
【7月更文挑战第18天】前后端分离采用Flask/Django框架,前端JavaScript框架如Vue.js与后端通过AJAX/Fetch通信。WebSocket提供实时双向通信,Python可借助websockets库或Flask-SocketIO实现。最佳实践包括定义清晰的接口规范,确保安全性(HTTPS,认证授权),优化性能,和健壮的错误处理。结合两者,打造高效实时应用。
86 1
|
19天前
|
前端开发 JavaScript UED
探索Python Django中的WebSocket集成:为前后端分离应用添加实时通信功能
通过在Django项目中集成Channels和WebSocket,我们能够为前后端分离的应用添加实时通信功能,实现诸如在线聊天、实时数据更新等交互式场景。这不仅增强了应用的功能性,也提升了用户体验。随着实时Web应用的日益普及,掌握Django Channels和WebSocket的集成将为开发者开启新的可能性,推动Web应用的发展迈向更高层次的实时性和交互性。
43 1
|
18天前
|
前端开发 JavaScript Python
Python Web应用中的WebSocket实战:前后端分离时代的实时数据交换
在前后端分离的Web应用开发模式中,如何实现前后端之间的实时数据交换成为了一个重要议题。传统的轮询或长轮询方式在实时性、资源消耗和服务器压力方面存在明显不足,而WebSocket技术的出现则为这一问题提供了优雅的解决方案。本文将通过实战案例,详细介绍如何在Python Web应用中运用WebSocket技术,实现前后端之间的实时数据交换。
36 0
|
18天前
|
运维 负载均衡 安全
深度解析:Python Web前后端分离架构中WebSocket的选型与实现策略
深度解析:Python Web前后端分离架构中WebSocket的选型与实现策略
55 0
|
3月前
|
监控 前端开发 API
实战指南:使用Python Flask与WebSocket实现高效的前后端分离实时系统
【7月更文挑战第18天】构建实时Web应用,如聊天室,可借助Python的Flask和WebSocket。安装Flask及Flask-SocketIO库,创建Flask应用,处理WebSocket事件。前端模板通过Socket.IO库连接服务器,发送和接收消息。运行应用,实现实时通信。此示例展现了Flask结合WebSocket实现前后端实时交互的能力。
428 3
|
19天前
|
安全 数据安全/隐私保护 UED
优化用户体验:前后端分离架构下Python WebSocket实时通信的性能考量
在当今互联网技术的迅猛发展中,前后端分离架构已然成为主流趋势,它不仅提升了开发效率,也优化了用户体验。然而,在这种架构模式下,如何实现高效的实时通信,特别是利用WebSocket协议,成为了提升用户体验的关键。本文将探讨在前后端分离架构中,使用Python进行WebSocket实时通信时的性能考量,以及与传统轮询方式的比较。
41 2
|
1月前
|
前端开发 JavaScript 安全
深入理解Python Web开发中的前后端分离与WebSocket实时通信技术
在现代Web开发中,前后端分离已成为主流架构,通过解耦前端(用户界面)与后端(服务逻辑),提升了开发效率和团队协作。前端使用Vue.js、React等框架与后端通过HTTP/HTTPS通信,而WebSocket则实现了低延迟的全双工实时通信。本文结合Python框架如Flask和Django,探讨了前后端分离与WebSocket的最佳实践,包括明确接口规范、安全性考虑、性能优化及错误处理等方面,助力构建高效、实时且安全的Web应用。
38 2
|
1月前
|
前端开发 Python
前后端分离的进化:Python Web项目中的WebSocket实时通信解决方案
在现代Web开发领域,前后端分离已成为一种主流架构模式,它促进了开发效率、提升了应用的可维护性和可扩展性。随着实时数据交互需求的日益增长,WebSocket作为一种在单个长连接上进行全双工通讯的协议,成为了实现前后端实时通信的理想选择。在Python Web项目中,结合Flask框架与Flask-SocketIO库,我们可以轻松实现WebSocket的实时通信功能。
47 2
|
1月前
|
JavaScript 前端开发 UED
WebSocket在Python Web开发中的革新应用:解锁实时通信的新可能
在快速发展的Web应用领域中,实时通信已成为许多现代应用不可或缺的功能。传统的HTTP请求/响应模式在处理实时数据时显得力不从心,而WebSocket技术的出现,为Python Web开发带来了革命性的变化,它允许服务器与客户端之间建立持久的连接,从而实现了数据的即时传输与交换。本文将通过问题解答的形式,深入探讨WebSocket在Python Web开发中的革新应用及其实现方法。
36 3
|
1月前
|
前端开发 API Python
WebSocket技术详解:如何在Python Web应用中实现无缝实时通信
在Web开发的广阔领域中,实时通信已成为许多应用的核心需求。传统的HTTP请求-响应模型在实时性方面存在明显不足,而WebSocket作为一种在单个长连接上进行全双工通信的协议,为Web应用的实时通信提供了强有力的支持。本文将深入探讨WebSocket技术,并通过一个Python Web应用的案例分析,展示如何在Python中利用WebSocket实现无缝实时通信。
35 2