Connecting to a WebSocket in Golang fails with bad handshake

Viewed 2574

I am trying to connect to a websocket in Golang using github.com/gorilla/websocket library but it's failing with a bad handshake.

Golang code :

    c, resp, err := websocket.DefaultDialer.Dial(WEBSOCKET_ENDPOINT, nil)
    if err != nil {
        fmt.Println(resp.Status)
        fmt.Println(err)
    }
    _ = c

Output :

200 OK
websocket: bad handshake

I also tried connecting to the same socket in python using socketio and it works.

Python code:

import socketio
sio = socketio.Client()
sio.connect(WEBSOCKET_ENDPOINT, transports = 'websocket')

@sio.event
def connect():
    print("I'm connected!")

Output :

I'm connected!
1 Answers

See What Socket.IO is not:

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.

In Go you are using Gorilla Websockets which is a standard Websocket client. Your Python example appears to be using python-socketio which is an implementation of Socket.IO.

As per the above quote the two are not directly compatible. I suspect your server is using Socket.IO and, as per the above quote, "a WebSocket client will not be able to successfully connect".

Related