Python中有没有实现的WebSocket客户端?

119 投票
5 回答
221018 浏览
提问于 2025-04-16 00:34

我找到一个项目:http://code.google.com/p/standalonewebsocketserver/,这是一个WebSocket服务器的项目。不过我需要在Python中实现一个WebSocket客户端,具体来说,我需要从XMPP接收一些命令到我的WebSocket服务器里。

5 个回答

10

最近我在这个领域做了一些研究(2012年1月),发现最有前景的客户端其实是:Python的WebSocket。它支持一种普通的套接字,你可以这样调用:

ws = EchoClient('http://localhost:9000/ws')

这个client可以是Threaded(多线程的)或者基于Tornado项目的IOLoop。这样你就可以创建一个可以同时处理多个连接的客户端。如果你想进行压力测试,这个功能会很有用。

这个客户端还提供了onmessageopenedclosed这些方法,都是WebSocket风格的。

24

Autobahn为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()
218

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()

撰写回答