我发现了这个项目: http://code.google.com/p/standalonewebsocketserver/,它提供了一个WebSocket服务器, 但是我需要在python中实现一个WebSocket客户端,更确切地说,我需要在我的WebSocket服务器中从XMPP接收一些命令。
我发现了这个项目: http://code.google.com/p/standalonewebsocketserver/,它提供了一个WebSocket服务器, 但是我需要在python中实现一个WebSocket客户端,更确切地说,我需要在我的WebSocket服务器中从XMPP接收一些命令。
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()
pip install
在Windows上很好用!我使用的是ActivePython 2.7,在命令行输入pip install websocket-client
就行了。唯一的问题是python
与cygwin的python冲突,所以我必须显式地运行/cygdrive/C/Python27/python
来获取ActivePython。 - Mark Lakatasudo
,用--user
。 - Dominik StańczakAutobahn提供了Python的优秀websocket客户端实现以及一些不错的示例。我用以下代码测试了Tornado WebSocket服务器并且它可以工作。
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()
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
是较新版本的 Autobahn 中正确的导入方式。https://dev59.com/13vaa4cB1Zd3GeqPHslX - evan54最近我在这个领域进行了一些研究(2012年1月),最有希望的客户端实际上是:WebSocket for Python。它支持一个普通的 socket,您可以像这样调用它:
ws = EchoClient('http://localhost:9000/ws')
client
可以是基于 IOLoop
或者基于 Tornado 项目的 Threaded
。这将允许您创建一个多并发连接客户端。如果您想运行压力测试,这是非常有用的。
此外,该客户端还暴露了 onmessage
、opened
和 closed
方法(类似 WebSocket)。
web2py有comet_messaging.py,它使用Tornado进行Websockets。可以在这里查看示例:http://vimeo.com/18399381和这里vimeo.com/18232653