我找到了这个项目:http ://code.google.com/p/standalonewebsocketserver/用于 WebSocket 服务器,但我需要在 python 中实现一个 WebSocket 客户端,更确切地说,我需要在我的 WebSocket 服务器中接收来自 XMPP 的一些命令。
问问题
180403 次
5 回答
190
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()
于 2012-06-19T16:45:46.237 回答
23
Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
class EchoClientProtocol(WebSocketClientProtocol):
def sendHello(self):
self.sendMessage("Hello, world!")
def onOpen(self):
self.sendHello()
def onMessage(self, msg, binary):
print "Got echo: " + msg
reactor.callLater(1, self.sendHello)
if __name__ == '__main__':
factory = WebSocketClientFactory("ws://localhost:9000")
factory.protocol = EchoClientProtocol
connectWS(factory)
reactor.run()
于 2012-01-18T17:01:06.193 回答
10
由于我最近(12 年 1 月)一直在该领域进行一些研究,因此最有前途的客户端实际上是:WebSocket for Python。它支持一个普通的套接字,你可以这样调用:
ws = EchoClient('http://localhost:9000/ws')
client
可以是或Threaded
基于Tornado项目。这将允许您创建一个多并发连接客户端。如果您想运行压力测试,这很有用。IOLoop
客户端还公开onmessage
,opened
和closed
方法。(WebSocket 样式)。
于 2012-01-09T13:19:07.210 回答
0
- 看看http://code.google.com/p/pywebsocket/下的echo客户端,是谷歌的项目。
- 在 github 中的一个很好的搜索是:https ://github.com/search?type=Everything&language=python&q=websocket&repo=&langOverride=&x=14&y=29&start_value=1它返回客户端和服务器。
- Bret Taylor 还通过 Tornado (Python) 实现了 Web 套接字。他的博客文章:Tornado 中的 Web Sockets和客户端实现 API 显示在客户端支持部分的tornado.websocket中。
于 2011-01-04T15:15:10.187 回答
-1
web2py 有 comet_messaging.py,它使用 Tornado 进行 websockets 看一个例子:http: //vimeo.com/18399381和这里 vimeo。com / 18232653
于 2011-01-04T16:31:08.033 回答