问题:是否有针对Python实现的WebSocket客户端?[关闭]
我找到了这个项目:http : //code.google.com/p/standalonewebsocketserver/用于WebSocket服务器,但是我需要在python中实现WebSocket客户端,更确切地说,我需要从WebSocket服务器中的XMPP接收一些命令。
回答 0
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()回答 1
高速公路为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()回答 2
自从我最近在该领域进行了一些研究(Jan,’12)以来,最有希望的客户实际上是:WebSocket for Python。它支持可以这样调用的普通套接字:
ws = EchoClient('http://localhost:9000/ws')该client可Threaded或基于IOLoop从龙卷风项目。这将允许您创建一个多并发连接客户端。如果要运行压力测试,则很有用。
客户端也暴露了onmessage,opened和closed方法。(WebSocket样式)。
回答 3
web2py有comet_messaging.py,它使用Tornado进行websockets,请在此处查看示例:http : //vimeo.com/18399381和此处vimeo。com / 18232653
回答 4
- 在http://code.google.com/p/pywebsocket/下查看回显客户端,这是一个Google项目。
- 在github中的一个很好的搜索是: https //github.com/search? = & = & = & =& =& =14& = & =1它返回客户端和服务器。
- Bret Taylor还通过Tornado(Python)实现了Web套接字。他的博客文章位于:Tornado中的Web套接字和客户端实现API,显示在客户端支持部分的tornado.websocket中。
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

