猿问

Gorilla Websocket:WebSocket 握手期间出错:意外响应代码:404

我克隆了 gorilla websocket 聊天示例并将其更新为使用多个房间。但是,我收到错误消息: Error during WebSocket handshake: Unexpected response code: 404 每当我尝试建立连接时在 chrome 中。我的源代码在github上可用。它与原始示例非常相似,只是略有改动。我不知道为什么它不起作用。


编辑:问题出现在这行代码中:


for _, name := range []string{"arduino", "java", "go", "scala"} {

    room := newRoom("go")

    http.Handle("/chat/go", room)

    go room.run()

}

循环切片会导致 httphandle 函数出现问题。相反,我单独声明它们:


room := newRoom("go")

http.Handle("/chat/go", room)

go room.run()

...

有用。我怎样才能解决这个问题?


慕丝7291255
浏览 347回答 1
1回答

精慕HU

所以实际上从你的index.html文件中,你连接到错误的 url<!-- index.html --><script>&nbsp; &nbsp; var serviceLocation = "ws://0.0.0.0:8080/chat/";.....&nbsp; &nbsp; function connectToChatserver() {&nbsp; &nbsp; &nbsp; &nbsp; room = $('#chatroom option:selected').val();&nbsp; &nbsp; &nbsp; &nbsp; wsocket = new WebSocket(serviceLocation + room);&nbsp; &nbsp; &nbsp; &nbsp; // it connect to /chat/<room>, it has slash after chat这是您的网址main.go&nbsp; &nbsp; http.Handle("/chat"+name, room)它会使 url 像这样:http://localhost:8080/chatgo,而不是你想要的:http://localhost:8080/chat/goFyi,它会因为你没有正确处理而出错channel,所以在我发送1条消息后,它会自动关闭。但这是另一个话题。2020/08/04 06:42:10 running chat room java2020/08/04 06:42:10 running chat room go2020/08/04 06:42:10 running chat room arduino2020/08/04 06:42:10 running chat room scala2020/08/04 06:42:15 new client in room arduino2020/08/04 06:42:15 client leaving room arduino2020/08/04 06:42:15 client leaving room arduinopanic: close of closed channelgoroutine 6 [running]:main.(*Room).run(0xc00007ac90)&nbsp; &nbsp; &nbsp; &nbsp; /home/fahim/Projects/Golang/go-chat/room.go:70 +0x3b5created by main.main&nbsp; &nbsp; &nbsp; &nbsp; /home/fahim/Projects/Golang/go-chat/main.go:17 +0x2bdexit status 2
随时随地看视频慕课网APP

相关分类

Go
我要回答