有没有为python实现的WebSocket客户端? [英] Is there a WebSocket client implemented for python?

查看:2261
本文介绍了有没有为python实现的WebSocket客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个专案: http://code.google.com/p/standalonewebsocketserver/ 对于websocket服务器,但我需要在python中实现websocket客户端,更准确地说,我需要从我的websocket服务器中的xmpp接收一些命令。

I found this project: http://code.google.com/p/standalonewebsocketserver/ for a websocket server, but I need to implement a websocket client in python, more exactly I need to receive some commands from xmpp in my websocket server.

推荐答案

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

这篇关于有没有为python实现的WebSocket客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆