【问题标题】:Websocket handshake fails 404 (golang server)Websocket握手失败404(golang服务器)
【发布时间】:2016-02-04 13:32:56
【问题描述】:

我有一个简单的 go web 服务器,它在端口 localhost:8080 上提供一个公共文件夹,其中包含一个 html 文件以及一个带有 websocket 逻辑的客户端脚本。

在我的main.go file

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 can't establish a connection to the server at ws://127.0.0.1:8080/.

我发现 this article 指的是 node.js,表示将 /websocket 添加到我的客户端 websocket 字符串中,尽管它没有解决问题并导致 404

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

【问题讨论】:

  • 服务器端(或 http 服务器的任何部分)的 Web 套接字处理代码在哪里?
  • @JimB 将要点添加到 main.go 文件,感谢您的反馈。
  • 您的代码仅侦听 tcp 套接字。您根本没有 http 或 websocket 处理代码。 Websockets 是 HTTP/1.1 en.wikipedia.org/wiki/WebSocket 的一部分

标签: javascript html go websocket


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 2019-02-25
  • 2011-12-26
  • 1970-01-01
相关资源
最近更新 更多