Websocket写入消息失败

huangapple go评论83阅读模式
英文:

Websocket Failure on WriteMessage

问题

我正在使用Go语言构建一个简单的Slackbot作为学习经验,但我遇到了第一个问题:我无法向连接写入消息!

这是我的主要函数:

func main() {
  conn, botId, err := slackInit(os.Getenv("SLACKBOT_TOKEN"))
  if err != nil { return }

  defer conn.Close()
  for {
    _, event, err := conn.ReadMessage()
    if err != nil {
      fmt.Println("Error processing message:", err)
      return
    }

    fmt.Println(string(event))

    message, err := slackGetMessage(event)
    if strings.Contains(message, botId) {
      fmt.Println("Bot was mentioned!")
      resp := []byte("You talkin' to me?")
      err = conn.WriteMessage(1, resp)
      if err != nil {
        fmt.Println("Error writing message:", string(resp))
        return
      }
    }
  }
}

这段代码可以监听并报告事件,但一旦调用conn.WriteMessage方法,就会失败。我从websocket得到一个致命错误,代码为1006,消息为"unexpected closure"。

我正在使用Gorilla作为我的websocket库,我怀疑这可能是与它们的"一个读者,一个写者"限制相关的并发问题。我尝试了一些调整,但实际上对于调试这个问题,我对这门语言/库还不够了解。:-/

我确定我在这里漏掉了一些明显的东西!有没有什么建议可以管理我的Writer,让我的机器人回应呢?谢谢!

英文:

I'm building out a simple Slackbot as a learning experience with Go, and I've hit my first snag: I'm unable to write a message back to the connection!

Here's my main func:

func main() {
  conn, botId, err := slackInit(os.Getenv("SLACKBOT_TOKEN"))
  if err != nil { return }

  defer conn.Close()
  for {
    _, event, err := conn.ReadMessage()
    if err != nil {
      fmt.Println("Error processing message:", err)
      return
    }

    fmt.Println(string(event))

    message, err := slackGetMessage(event)
    if strings.Contains(message, botId) {
      fmt.Println("Bot was mentioned!")
      resp := []byte("You talkin' to me?")
      err = conn.WriteMessage(1, resp)
      if err != nil {
        fmt.Println("Error writing message:", string(resp))
        return
      }
    }
  }
}

This listens and reports events with no issue, but fails as soon as the conn.WriteMessage method is called. I get a fatal error from websocket with code 1006 & the message "unexpected closure".

I'm using Gorilla for my websocket library, and I suspect maybe this is a concurrency issue related to their "one reader, one writer" limit. I've tried a few tweaks, but honestly just don't know enough about the languge/library yet to really dive deep on debugging this. :-/

I'm sure I'm missing something obvious here! Any tips for managing my Writer to get my bot talking back? Thanks!

答案1

得分: 1

发送到服务器的消息不是服务器所期望的 JSON 格式。服务器在没有握手的情况下关闭了连接。

英文:

The message sent to the server is not JSON as expected by the server. The server closed the connection without a handshake.

huangapple
  • 本文由 发表于 2016年12月10日 06:27:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/41069869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定