是否有为 Python 实现的 WebSocket 客户端? [英] Is there a WebSocket client implemented for Python?
本文介绍了是否有为 Python 实现的 WebSocket 客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我找到了这个项目:http://code.google.com/p/standalonewebsocketserver/ 对于 WebSocket 服务器,但我需要在 python 中实现一个 WebSocket 客户端,更确切地说,我需要在我的 WebSocket 服务器中从 XMPP 接收一些命令.
I found this project: http://code.google.com/p/standalonewebsocketserver/ for a WebSocket server, but I need to implement a WebSocket client in python, more exactly I need to receive some commands from XMPP in my WebSocket server.
推荐答案
http://pypi.python.org/pypi/websocket-client/
非常容易使用.
sudo pip install websocket-client
示例客户端代码:
#!/usr/bin/python
from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Receiving..."
result = ws.recv()
print "Received '%s'" % result
ws.close()
示例服务器代码:
#!/usr/bin/python
import websocket
import thread
import time
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run(*args):
for i in range(30000):
time.sleep(1)
ws.send("Hello %d" % i)
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://echo.websocket.org/",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
这篇关于是否有为 Python 实现的 WebSocket 客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文