登录
首页 >  Golang >  Go问答

无法与“ws://localhost:8080/”建立 WebSocket 连接:在 WebSocket 握手期间发生错误:意外的 404 响应代码

来源:stackoverflow

时间:2024-02-17 09:03:22 300浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《无法与“ws://localhost:8080/”建立 WebSocket 连接:在 WebSocket 握手期间发生错误:意外的 404 响应代码》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

与“ws://localhost:8080/websocket”的 websocket 连接失败:websocket 握手期间出错:意外的响应代码:404,当我尝试将 websocket 从 reactjs 连接到我创建的 backend(go) 时,会发生这种情况处理程序,这是我的后端代码路由器文件

import (
    "net/http"

    "../server"
    "github.com/gorilla/mux"
)

// router is exported and used in main.go
func router() *mux.router {

    router := mux.newrouter().strictslash(true)
    router.handlefunc("/ws", server.handleconnections) //
    router.handlefunc("/api/block", server.getallblock).methods("get", "options")
    router.handlefunc("/api/block", server.createblock).methods("post", "options")

    router.pathprefix("/").handler(http.fileserver(http.dir("../public")))

    return router
}

这是我的主要内容

func runwebserver() {
    r := router.router()


    fmt.println("starting server on the port 8080...")
    log.fatal(http.listenandserve("localhost:8080", r))
}

func main() {
     go runwebserver()
}

这是我的handleconnection函数

func handleconnections(w http.responsewriter, r *http.request) {
    fmt.println("in handle")

    ws, err := upgrader.upgrade(w, r, nil)
    if err != nil {
        log.fatal(err)
        fmt.println("error in ebss")
    }
    fmt.println("no error")
    // make sure we close the connection when the function returns
    //  defer ws.close()

    // register our new client
    nodes[ws] = true

    for {
        // read in a new message as json and map it to a message object
        var course course
        err := ws.readjson(&course)
        if err != nil {
            log.printf("error: %v", err)
            //  delete(nodes, ws)
            break
        }

        // send the newly received message to the broadcast channel
        broadcast <- course
    }

}

这是我的前端 react 文件,其中发生了 404 握手错误

let endpoint = "http://localhost:8080";

    class Blockchain extends Component {
      componentDidMount() {
        let ws = new WebSocket('ws://localhost:8080');//Here
        console.log("webs",ws)
      }

这是加载页面时浏览器中显示的错误


解决方案


这是您的主要问题:

func main() {
     go runwebserver()
}

这会在一个单独的 goroutine 中运行 runwebserver 函数,这使得主 goroutine(main() 函数调用)继续经过该行。由于 main 函数中不再有指令,因此程序返回。当 go 程序返回时,所有子 goroutine 都会返回。不能依赖该程序执行任何操作,因为 main goroutine 返回得太快。

您应该像下面这样以阻塞方式运行该函数,或者看看管理多个 goroutine。 This guide 可能是一个不错的起点。

func main() {
     runWebServer()
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>