尝试为Python3支持的应用程序创建Web前端.该应用程序将需要双向流,这听起来像是查看websockets的好机会.
我的第一个倾向是使用已经存在的东西,mod-pywebsocket的示例应用程序已被证明是有价值的.不幸的是,他们的API似乎并不容易扩展,而且它是Python2.
环顾博客圈,许多人为早期版本的websocket协议编写了自己的websocket服务器,大多数人都没有实现安全密钥哈希所以不行.
阅读RFC 6455我决定自己尝试一下,并提出以下建议:
#!/usr/bin/env python3
"""
A partial implementation of RFC 6455
http://tools.ietf.org/pdf/rfc6455.pdf
Brian Thorne 2012
"""
import socket
import threading
import time
import base64
import hashlib
def calculate_websocket_hash(key):
magic_websocket_string = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
result_string = key + magic_websocket_string
sha1_digest = hashlib.sha1(result_string).digest()
response_data = base64.encodestring(sha1_digest)
response_string = response_data.decode('utf8')
return response_string
def is_bit_set(int_type, offset):
mask = 1 << offset
return not 0 == (int_type & mask)
def set_bit(int_type, offset):
return int_type | (1 << offset)
def bytes_to_int(data): …Run Code Online (Sandbox Code Playgroud) 我想用pywebsocket测试websocket ,经过我在互联网上发现的一些指令后的一些配置,我终于得到它运行.
然后我想尝试回声示例:http://code.google.com/p/pywebsocket/source/browse/trunk/src/example/console.html
websocket连接成功,我可以做那些发送和接收但是,自从建立websocket大约10秒后,自动关闭了websocket.每次它都像这样工作.我使用apache在Ubuntu 11.04上使用Chromium 11进行了测试.有任何想法吗?
我编写了一个多线程Web套接字客户端类,以便用户的(主)线程不会阻塞run_forever()方法调用.代码似乎工作正常,除了最后,当我停止线程时,它不会干净地关闭Web套接字,我的进程不会退出.我kill -9每次都要做一个摆脱它.我尝试调用线程的join()方法来确保主线程等待子进程完成执行,但这没有帮助.
代码如下所示.你能帮助我退出/停止线程优雅吗?
import thread
import threading
import time
import websocket
class WebSocketClient(threading.Thread):
def __init__(self, url):
self.url = url
threading.Thread.__init__(self)
def run(self):
# Running the run_forever() in a seperate thread.
#websocket.enableTrace(True)
self.ws = websocket.WebSocketApp(self.url,
on_message = self.on_message,
on_error = self.on_error,
on_close = self.on_close)
self.ws.on_open = self.on_open
self.ws.run_forever()
def send(self, data):
# Wait till websocket is connected.
while not self.ws.sock.connected:
time.sleep(0.25)
print 'Sending data...', data
self.ws.send("Hello %s" % data)
def stop(self):
print 'Stopping the websocket...' …Run Code Online (Sandbox Code Playgroud)