我想用python编写一个简单的socket.io客户端,以连接到通常通过浏览器+ javascript访问的外部socket.io服务器的特定名称空间。
在浏览器中,连接的工作方式如下:
首先,页面https://url:port/socket.io/1/?t=1562423475873被加载,返回类似于ACKHJADICSBVFUIASBFAKJSDN:60:60:websocket,xhr-polling,jsonp-polling
然后,建立了与wss://url:port/socket.io/1/websocket/ACKHJADICSBVFUIASBFAKJSDN
的连接
对于python,我编写了以下代码。
import socketio
sio = socketio.Client(logger=True, engineio_logger=True)
class MyCustomNamespace(socketio.ClientNamespace):
def on_connect(self):
print("I'm connected!")
def on_disconnect(self):
print("I'm disconnected!")
sio.register_namespace(MyCustomNamespace('/ns'))
socketiopath = "socket.io/1/"
sio.connect("https://url:port", namespaces=["/ns"], socketio_path=socketiopath, transports=["websocket"])
while True:
sio.wait()
此代码无效。消息“我已连接!”不打印。 我得到以下记录器输出:
Attempting WebSocket connection to wss://url:port/socket.io/1/?transport=websocket&EIO=3
Traceback (most recent call last):
File "test.py", in <module>
sio.connect("https://url:port", namespaces=["/ns"], socketio_path=socketiopath, transports=["websocket"])
File "/home/user/.local/lib/python3.6/site-packages/socketio/client.py", line 244, in connect
engineio_path=socketio_path)
File "/home/user/.local/lib/python3.6/site-packages/engineio/client.py", line 166, in connect
url, headers, engineio_path)
File "/home/user/.local/lib/python3.6/site-packages/engineio/client.py", line 341, in _connect_websocket
cookie=cookies)
File "/home/user/.local/lib/python3.6/site-packages/websocket/_core.py", line 514, in create_connection
websock.connect(url, **options)
File "/home/user/.local/lib/python3.6/site-packages/websocket/_core.py", line 226, in connect
self.handshake_response = handshake(self.sock, *addrs, **options)
File "/home/user/.local/lib/python3.6/site-packages/websocket/_handshake.py", line 79, in handshake
status, resp = _get_resp_headers(sock)
File "/home/user/.local/lib/python3.6/site-packages/websocket/_handshake.py", line 158, in _get_resp_headers
status, resp_headers, status_message = read_headers(sock)
File "/home/user/.local/lib/python3.6/site-packages/websocket/_http.py", line 305, in read_headers
line = recv_line(sock)
File "/home/user/.local/lib/python3.6/site-packages/websocket/_socket.py", line 123, in recv_line
c = recv(sock, 1)
File "/home/user/.local/lib/python3.6/site-packages/websocket/_socket.py", line 115, in recv
"Connection is already closed.")
websocket._exceptions.WebSocketConnectionClosedException: Connection is already closed.
你能告诉我,我想念什么吗?