python简单实现websocket

上传人:灯火****19 文档编号:122349143 上传时间:2020-03-04 格式:DOC 页数:5 大小:89.14KB
返回 下载 相关 举报
python简单实现websocket_第1页
第1页 / 共5页
python简单实现websocket_第2页
第2页 / 共5页
python简单实现websocket_第3页
第3页 / 共5页
python简单实现websocket_第4页
第4页 / 共5页
python简单实现websocket_第5页
第5页 / 共5页
亲,该文档总共5页,全部预览完了,如果喜欢就下载吧!
资源描述

《python简单实现websocket》由会员分享,可在线阅读,更多相关《python简单实现websocket(5页珍藏版)》请在金锄头文库上搜索。

1、python简单实现websocket协议选择的是新的Hybi-10,参考文章如下:http:/ coding:utf8 -*-import threadingimport hashlibimport socketimport base64class websocket_thread(threading.Thread): def _init_(self, connection): super(websocket_thread, self)._init_() self.connection = connection def run(self): print new websocket clien

2、t joined! reply = i got u, from websocket server. length = len(reply) while True: data = self.connection.recv(1024) print parse_data(data) self.connection.send(%c%c%s % (0x81, length, reply) def parse_data(msg): v = ord(msg1) & 0x7f if v = 0x7e: p = 4 elif v = 0x7f: p = 10 else: p = 2 mask = msgp:p+

3、4 data = msgp+4: return .join(chr(ord(v) ord(maskk%4) for k, v in enumerate(data) def parse_headers(msg): headers = header, data = msg.split(rnrn, 1) for line in header.split(rn)1: key, value = line.split(: , 1) headerskey = value headersdata = data return headersdef generate_token(msg): key = msg +

4、 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 ser_key = hashlib.sha1(key).digest() return base64.b64encode(ser_key) if _name_ = _main_: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(127.0.0.1, 9000) sock.listen(5) while True: co

5、nnection, address = sock.accept() try: data = connection.recv(1024) headers = parse_headers(data) token = generate_token(headersSec-WebSocket-Key) connection.send(HTTP/1.1 101 WebSocket Protocol Hybi-10rnUpgrade: WebSocketrnConnection: UpgradernSec-WebSocket-Accept: %srnrn % token) thread = websocke

6、t_thread(connection) thread.start() except socket.timeout: print websocket connection timeout测试页面: WebSocketTest 来自服务端的消息 var socket; function connect() var host = ws:/ + $(serverIP).value + : + $(serverPort).value + / socket = new WebSocket(host); try socket.onopen = function (msg) $(btnConnect).di

7、sabled = true; alert(连接成功!); ; socket.onmessage = function (msg) if (typeof msg.data = string) displayContent(msg.data); else alert(非文本消息); ; socket.onclose = function (msg) alert(socket closed!) ; catch (ex) log(ex); function send() var msg = $(sendText).value socket.send(msg); window.onbeforeunloa

8、d = function () try socket.close(); socket = null; catch (ex) ; function $(id) return document.getElementById(id); Date.prototype.Format = function (fmt) /author: meizz var o = M+: this.getMonth() + 1, /月份 d+: this.getDate(), /日 h+: this.getHours(), /小时 m+: this.getMinutes(), /分 s+: this.getSeconds(), /秒 q+: Math.floor(this.getMonth() + 3) / 3), /季度 S:

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > IT计算机/网络 > 其它相关文档

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号