繁体   English   中英

Websocket握手失败404(golang服务器)

[英]Websocket handshake fails 404 (golang server)

我有一个简单的Go Web服务器,该服务器在localhost:8080端口上提供一个公用文件夹,该公用文件夹同时包含html文件以及具有websocket逻辑的客户端脚本。

在我的main.go文件中

listener, err := net.listen("tcp", "localhost:8080")
if err != nil {
    log.Fatal(err)
}
//full code in gist https://gist.github.com/Kielan/98706aaf5dc0be9d6fbe

然后在我的客户脚本中

try {
    var sock = new WebSocket("ws://127.0.0.1:8080");
    console.log("Websocket - status: " + sock.readyState);

    sock.onopen = function(message) {
    console.log("CONNECTION opened..." + this.readyState);
    //onmessage, onerr, onclose, ect...
}

我在Chrome中收到错误

WebSocket connection to 'ws://127.0.0.1:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200

和Firefox

Firefox can't establish a connection to the server at ws://127.0.0.1:8080/.

我发现这篇文章涉及到node.js,指示将/ websocket添加到我的客户端websocket字符串中,尽管它不能解决问题并导致404

我认为响应码200很好,是否需要以某种方式将请求转换为websocket,也许默认为http? 如果可以,我该怎么做?

就像JimB指出的那样,您尚未处理http或websocket连接。

您可以使用包github.com/gorilla/websocket进行websocket处理。这是一个简单的设置:

package main

import (    
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

// wsHandler implements the Handler Interface
type wsHandler struct{}

func main() {
    router := http.NewServeMux()
    router.Handle("/", http.FileServer(http.Dir("./webroot"))) //handles static html / css etc. under ./webroot
    router.Handle("/ws", wsHandler{}) //handels websocket connections

    //serving
    log.Fatal(http.ListenAndServe("localhost:8080", router))
}

func (wsh wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // upgrader is needed to upgrade the HTTP Connection to a websocket Connection
        upgrader := &websocket.Upgrader{
            ReadBufferSize:  1024,
            WriteBufferSize: 1024,
        }

        //Upgrading HTTP Connection to websocket connection
        wsConn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            log.Printf("error upgrading %s", err)
            return
        }

        //handle your websockets with wsConn
}

然后,在您的Javascript中,需要var sock = new WebSocket("ws://localhost/ws:8080"); 明显。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM