首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Websocket握手失败404 (golang服务器)

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

Stack Overflow用户
提问于 2016-02-04 13:32:56
回答 1查看 3.3K关注 0票数 0

我有一个简单的go web服务器,它服务于端口localhost:8080,这是一个包含html文件和带有websocket逻辑的客户端脚本的公用文件夹。

在我的main.go文件

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

然后在我的客户脚本中

代码语言:javascript
复制
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...
}

我得到了铬的错误

代码语言:javascript
复制
WebSocket connection to 'ws://127.0.0.1:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200

和火狐

代码语言:javascript
复制
Firefox can't establish a connection to the server at ws://127.0.0.1:8080/.

我发现这篇文章引用了node.js,指示要将/websocket添加到我的客户端websocket字符串中,尽管它没有解决问题,导致了404。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-04 14:31:06

正如JimB所指出的,您还没有处理http或websocket连接。

您可以对包github.com/gorilla/websocket进行websocket处理--这是一个简单的设置的样子:

代码语言:javascript
复制
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");

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35202405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档