others - Python是否有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"Reeiving..."


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



Autobahn有一个好的python的web socket客户端实现,以及一些好的例子,我用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()



...