Node websocket客户端监听Golang websocket服务器

时间:2018-04-16 19:58:34

标签: node.js go websocket

我正在尝试使用Golang websocket发布消息,并在Node客户端监听。

以下是代码的一部分:

Golang:

https://api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest/getCreateObjectOptions

通过这样做,我可以在Google控制台上运行以下代码时收到所有消息

func NewUpgrader() *websocket.Upgrader { return &websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } func (s WebsocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { upgrader := NewUpgrader() ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Errorf("websocket: could not upgrade %v", err) fmt.Fprintf(w, "websocket: could not upgrade %v", err) return } go func() { defer ws.Close() for msg := range s.Messages { json, _ := json.Marshal(msg) err := ws.WriteMessage(1, json) if err != nil { log.Errorf("websocket: error sending message: %v", err) } } }()

我在客户端添加了相同的两行代码,现在我收到了这些错误

Golang方面:

ws = new WebSocket('ws://localhost:8080/ws') ws.onmessage = function(msg) { console.log(JSON.parse(msg.data)) }

客户端(浏览器控制台):

INFO[0009] 400 GET localhost:8080/ws (0 bytes) id: 77b7355412f2ffcd ERRO[0009] websocket: could not upgrade websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header

我尝试比较这两个获取请求(Google控制台与我的客户端代码)。我发现谷歌控制台有一个标题GET http://localhost:8080/ws 400 (Bad Request) Failed to load http://localhost:8080/ws: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Uncaught (in promise) TypeError: Failed to fetch,但标题在我的客户端代码中看起来像Connection:[Upgrade]

不确定这是否是我无法连接这两个想法的原因?

谢谢!

0 个答案:

没有答案