【问题标题】:Gorilla Websocket: Error during WebSocket handshake: Unexpected response code: 404Gorilla Websocket:WebSocket 握手期间出错:意外响应代码:404
【发布时间】:2020-11-24 00:45:23
【问题描述】:

我克隆了 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()
...

它有效。我该如何解决这个问题?

【问题讨论】:

  • 嗨,我检查了你的代码,它可以工作ibb.co/y023X26。您的操作系统和 Golang 版本是什么?
  • @FahimBagar 我认为您获取了错误的链接。它在“房间”分支下

标签: go websocket http-status-code-404 handshake gorilla


【解决方案1】:

所以实际上从您的index.html 文件中,您连接到了错误的网址

<!-- index.html -->
<script>
    var serviceLocation = "ws://0.0.0.0:8080/chat/";
.....

    function connectToChatserver() {
        room = $('#chatroom option:selected').val();
        wsocket = new WebSocket(serviceLocation + room);
        // it connect to /chat/<room>, it has slash after chat

这是您来自main.go的网址

    http.Handle("/chat"+name, room)

它会使 url 像这样:http://localhost:8080/chatgo,而不是你想要的:http://localhost:8080/chat/go

Fyi,因为你没有正确处理channel,所以会报错,所以在我发送1条消息后,它会自动关闭。但这是另一个话题。

2020/08/04 06:42:10 running chat room java
2020/08/04 06:42:10 running chat room go
2020/08/04 06:42:10 running chat room arduino
2020/08/04 06:42:10 running chat room scala
2020/08/04 06:42:15 new client in room arduino
2020/08/04 06:42:15 client leaving room arduino
2020/08/04 06:42:15 client leaving room arduino
panic: close of closed channel

goroutine 6 [running]:
main.(*Room).run(0xc00007ac90)
        /home/fahim/Projects/Golang/go-chat/room.go:70 +0x3b5
created by main.main
        /home/fahim/Projects/Golang/go-chat/main.go:17 +0x2bd
exit status 2

【讨论】:

  • 谢谢!那解决了它。我知道这很愚蠢:)。我修复了频道关闭错误。谢谢
猜你喜欢
  • 2015-03-21
  • 2019-10-15
  • 2019-09-06
  • 1970-01-01
  • 2015-12-26
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
相关资源
最近更新 更多