【问题标题】:Run web-Socket locally for debug在本地运行 web-Socket 进行调试
【发布时间】:2018-05-18 01:26:44
【问题描述】:

我正在使用 gorilla web socket,我想在本地运行它,我的意思是使用以下 chrome 客户端 或其他推荐的工具……当我进入调试模式时出现错误

我用

"github.com/gorilla/websocket"


var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

upgrader.CheckOrigin = func(r *http.Request) bool { return true }

c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
    log.Print("upgrade:", err)
    return
}

当我在 chrome 或 web socket 客户端中运行以下 url 时出现错误

websocket:不是 websocket 握手:在“连接”标头中找不到“升级”令牌

localhost:8081/mypath

我想运行它

ws://localhost:8081/mypath

并为本地模拟提供令牌,我该怎么做?

为了检查它,我使用了 chrome 的 Simple WebSocket Client。任何其他客户都会有所帮助

编辑:

当我在 chrome 控制台中尝试时,出现以下错误:

VM42:164 拒绝连接到 'ws://localhost:8081/mypath' 因为它 违反以下内容安全策略指令:“connect-src 'self' uploads.github.com status.github.com collector.githubapp.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com wss://live.github.com

【问题讨论】:

标签: go websocket


【解决方案1】:

浏览器在获取网页进行显示时不使用 WebSocket 协议。从浏览器使用 WebSocket 端点需要代码。

Gorilla 软件包包括 examples,展示了如何从浏览器进行连接(chatcommand 示例是很好的起点)。

您可以使用浏览器控制台连接到 WebSocket 端点:

> ws = new WebSocket("ws://localhost:8080/mypath")
> ws.onmessage = function(ev) { console.log(ev.data) }
> ws.send("hello")

【讨论】:

  • 非常感谢,我已经尝试过了,但出现错误,请查看我的编辑,有什么想法吗?
  • 对不起,第二次尝试它工作 1+,有没有办法从单元测试中运行它?如果是,你能提供例子吗?
  • @RaynD 使用 net/http/httptest 服务器和 Gorilla websocket 客户端从测试中使用。询问新问题以了解详情。
  • 好的,谢谢,只是在这种情况下的最后一个问题,我应该如何在 go 文件(ws 处理程序)中从客户端打印 hello 消息,我在 w obj 中看不到它...
  • 从读/写循环at the beginning of the documentation开始。阅读留言后,log.Printf("%s", p)查看收到的留言。