WebSocket握手失败:收到意外的404响应代码
时间:2024-02-27
浏览:266
作者:佚名
大家好,我们又见面了啊~本文《WebSocket握手失败:收到意外的404响应代码》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~
问题内容
我克隆了 gorilla websocket 聊天示例并将其更新为使用多个房间。但是,我收到错误:
websocket 握手期间出错:意外响应代码: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()
...
它有效。我该如何解决这个问题?
解决方案
实际上,从您的 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)
它将生成这样的网址:http://localhost:8080/chatgo,而不是您想要的:http://localhost:8080/chat/go
仅供参考,会报错,因为你没有正确处理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以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
