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

标签 javascript html go websocket

我有一个简单的 go web 服务器,它在端口 localhost:8080 上提供一个公共(public)文件夹,其中包含一个 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?如果可以,我该怎么做?

最佳答案

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

关于javascript - Websocket 握手失败 404(golang 服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35202405/

相关文章:

mongodb - 计算与 Mgo 中的查询匹配的文档数

gogo.proto : File not found

javascript - Ajax 从输入值更新分数

javascript - Firebase 身份验证不适用于 html 表单元素

asp.net - 不可选中的 RadioButtons 与独占的 Checkboxes

html - 旋转 div、绝对定位和响应性

arrays - 将json单元素数组转为字符串

php - PHP根据IF语句调用JS函数的问题

javascript - 基本 Javascript 问题 : How to open a new window?

javascript - 如何使用 javascript 中的坐标突出显示字符串中的单词?