7

I want to connect to Socket.IO server using python. Is there a way to do it?

I have tried websocket-client as suggested in this answer.

ws = create_connection("ws://example.com:1000/socket.io/")

That code throws this exception

websocket._exceptions.WebSocketConnectionClosedException: Connection is already closed.

I feel like I am missing parameters because the JS client connection URL looks like this:

ws://example.com:1000/socket.io/?EIO=3&transport=websocket&sid=CHARSANDNUMBERS
Community
  • 1
  • 1
Atrotors
  • 765
  • 2
  • 7
  • 25

2 Answers2

4

You just need to use the url from the JS client, possibly without the sid:

ws = create_connection("ws://example.com:1000/socket.io/?EIO=3&transport=websocket")

From my personal experience I didn't have that sid param, but just try to add it if it doesn't work without.

kluu
  • 41
  • 2
  • "Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either." ([source](https://socket.io/docs/v4/#what-socketio-is-not)) – bitinerant Apr 15 '23 at 07:56
1

You can look at this: socketIO-client

As an example,

from socketIO_client import SocketIO

socketIO = SocketIO('localhost', 8000)
mbtamuli
  • 697
  • 1
  • 7
  • 19