gpt4 book ai didi

python-websocket 和 socket.io 命名空间

转载 作者:行者123 更新时间:2023-11-28 16:48:28 26 4
gpt4 key购买 nike

我会用 python 编写一个 websocket 客户端来连接到一个用 socket.io 编写的服务器。我当前的代码,取自 1是以下内容:

import websocket, httplib, sys, asyncore
def connect(server, port):

print("connecting to: %s:%d" %(server, port))

conn = httplib.HTTPConnection(server + ":" + str(port))
conn.request('POST','/socket.io/1/')
resp = conn.getresponse()
hskey = resp.read().split(':')[0]
ws = websocket.WebSocket(
'ws://'+server+':'+str(port)+'/socket.io/1/websocket/'+hskey,
onopen = _onopen,
onmessage = _onmessage,
onclose = _onclose)

return ws

def _onopen():
print("opened!")

def _onmessage(msg):
print("msg: " + str(msg))

def _onclose():
print("closed!")


if __name__ == '__main__':

server = 'localhost'
port = 8081

ws = connect(server, port)

try:
asyncore.loop()
except KeyboardInterrupt:
ws.close()

我的问题是如何连接到特定的命名空间?

谢谢

最佳答案

您可以使用 socketIO-client在 MIT 许可证下可在 PyPI 上使用。它支持单个套接字的不同命名空间。

from socketIO_client import SocketIO, BaseNamespace

class MainNamespace(BaseNamespace):

def on_aaa(self, *args):
print 'aaa', args

class ChatNamespace(BaseNamespace):

def on_bbb(self, *args):
print 'bbb', args

class NewsNamespace(BaseNamespace):

def on_ccc(self, *args):
print 'ccc', args

mainSocket = SocketIO('localhost', 8000, MainNamespace)
chatSocket = mainSocket.connect('/chat', ChatNamespace)
newsSocket = mainSocket.connect('/news', NewsNamespace)
mainSocket.wait()

关于python-websocket 和 socket.io 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11098514/

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