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



>我有一个简单的go网络服务器,它在端口localhost:8080上提供服务,这是一个包含html文件和带有websocket逻辑的客户端脚本的公共文件夹。

在我的主.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...
}

我在铬中收到错误

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

和火狐

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");

相关内容

  • 没有找到相关文章

最新更新