gpt4 book ai didi

python - 使用自定义 socket.io 事件将 Python 客户端连接到 Socket.io

转载 作者:搜寻专家 更新时间:2023-11-01 00:45:28 25 4
gpt4 key购买 nike

我有一个 socket.io 服务器(在 node.js 中),我正在尝试将 python 客户端连接到它,主要是为我的套接字服务器提供命令行界面。

我正在使用 Python 的网络套接字,但是,我意识到它只支持四种“事件”:打开、关闭、错误和消息。

我的 socket.io 服务器定义了自定义事件,例如 .on('connection')。我如何在 python 中发出/接收此类自定义事件?

到目前为止,这是我的脚本,它只是启动和关闭,所以它不起作用。 导入网络套接字、请求、线程、时间 主机='http://socket-url-server.com '

def on_open(ws):
def run(*args):
print 'did connect'
for i in range(3):
time.sleep(1)
result = ws.recv()
print 'received:'
print result
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())

def on_message(ws, message):
print message

def on_error(ws, error):
print error

def on_close(ws):
print "### closed ###"

print('Connecting to %s' % host)

socket = host.replace('http://', 'ws://')
print socket
websocket.enableTrace(True)
_ws = websocket.WebSocketApp(socket,
on_message = on_message,
on_error = on_error,
on_close = on_close)
_ws.on_open = on_open
_ws.run_forever()

否则我应该使用哪个库/方法?如果我握手并自己获取 socket.io 服务器 key ,我该如何在之后发出/接收事件?

我也试过使用 https://pypi.python.org/pypi/socketIO-client , 但它的文档很差

我在下面为其编写了以下脚本,但我得到 No handlers could be found for logger "socketIO_client" 并且它永远挂起。

from socketIO_client import SocketIO, BaseNamespace

class Namespace(BaseNamespace):

def on_connect(self):
print '[Connected]'

socketIO = SocketIO('http://socket-server-url.com', 80, Namespace)
socketIO.wait(seconds=1)

最佳答案

我遇到了同样的问题,并且自己解决了这个问题。在这里,我写了一些关于库 socketIO_client 的使用的评论,希望它能有所帮助。

开发环境:Server/Client:python编写的nodejs/sio_client

  1. “找不到记录器“socketIO_client”的处理程序。这意味着它需要用于记录内容的处理程序。尝试“导入日志记录; logging.basicConfig(level=logging.DEBUG)"并记录下来。
  2. “socketio_client 永远挂起”因为它不断地重新连接到指定的服务器,即 Namespace 对象将不会被采用,直到 socketIO 对象被初始化并返回。我有其他线程(称为 thr_siohandle)初始化 socketio 对象,主线程使用命名空间中包含的队列,以检查是否有来自服务器的响应。看来在运行 sio_client 之前,您的服务器应该一直可以访问,否则它会一直重新连接,除非您停止该程序。虽然您可以将 wait_for_connection 设置为 True 以停止它,但您必须自己处理 socketIO_client.exceptions.ConnectionError

仅供引用

[2014/02/19]抱歉,请允许我在有关 py_SIOClient 的回答中附加一些评论。

示例代码如下:

class ChatNamespace(BaseNamespace):
def on_connect( self ):
print "connected."
def on_sayhello_response( self, data ):
print "response:", data

sio = SocketIO(host, port, ChatNamespace)
chatns = sio.define(ChatNamespace, '/chat')

while (1):
chatns.emit('sayhello', {'name':'John'})
chatns.wait(1)

此示例中的命令“sayhello”在重置连接时将处于非事件状态,并且不再可以访问命名空间对象 chatns(也没有出现错误)。因此,可以通过每次在发出消息之前重新定义专用命名空间来解决这个问题,因为我们不知道连接何时会被重置(我认为这无关紧要)。希望它对使用 py_SocketIO_Client 的人有所帮助。

补充 2014/09/09因为我使用 node(.js) 作为后端服务器,但是这个库似乎几个月没有更新,它的 socket.io 只支持 socket.io < 1.0.0。提醒您在选择此库之前请检查您的软件包版本。希望它能帮助像我一样面临同样问题的人。

关于python - 使用自定义 socket.io 事件将 Python 客户端连接到 Socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19934188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com