duanba2001 2018-04-16 19:58
浏览 120

节点websocket客户端侦听Golang websocket服务器

I am trying to post messages using Golang websocket and listen on Node client side.

Here's part of code:

Golang:

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)
            }
        }
    }()

By doing this I can get all the messages when I run the code below on Google console

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

And I add the same two lines code on my client side, now I got these errors

Golang side:

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

Client side(browser console):

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

I tried to compare these two get request(Google console vs my client-side code). I found out that for google console there's a header Connection:[Upgrade], but the header looks like this Connection:[keep-alive] in my client-side code.

Not sure if this is the reason why I can not connect these two, any ideas?

Thanks!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器