在Golang中连接WebSocket时出现握手失败的问题。

huangapple go评论77阅读模式
英文:

Connecting to a WebSocket in Golang fails with bad handshake

问题

我正在尝试使用github.com/gorilla/websocket库在Golang中连接到一个websocket,但是它在握手时失败了。

Golang代码:

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

输出:

200 OK
websocket: bad handshake

我还尝试使用Python中的socketio连接到相同的socket,它可以正常工作。

Python代码:

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

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

输出:

I'm connected!
英文:

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

得分: 1

请参考Socket.IO 不是什么

虽然 Socket.IO 在可能的情况下确实使用 WebSocket 进行传输,但它还会向每个数据包添加附加元数据。这就是为什么 WebSocket 客户端无法成功连接到 Socket.IO 服务器,而 Socket.IO 客户端也无法连接到普通的 WebSocket 服务器的原因。

在 Go 中,您正在使用 Gorilla Websockets,这是一个标准的 WebSocket 客户端。您的 Python 示例似乎在使用 python-socketio,它是 Socket.IO 的一个实现。

根据上述引用,这两者不是直接兼容的。我怀疑您的服务器正在使用 Socket.IO,并且根据上述引用,“WebSocket 客户端无法成功连接”。

英文:

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".

huangapple
  • 本文由 发表于 2022年3月9日 03:44:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/71400664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定