【问题标题】:http.Handle("/", websocket.Handler(EchoServer) Can EchoServer Get another parameter other than ws?http.Handle("/", websocket.Handler(EchoServer) EchoServer 能否获取除ws以外的其他参数?
【发布时间】:2014-05-21 23:27:57
【问题描述】:

我已经打开了一个 websocket 服务器来向 web 组件发送数据,

func WebSocketServer() {
    http.Handle("/", websocket.Handler(Echoserver))
    err := http.ListenAndServe(":8081", nil)
    CheckError(err)
}

我想将一个附加参数(msg,字符串类型)传递给处理函数(Echoserver)。

func Echoserver(ws *websocket.Conn, msg String) {
    fmt.Println("Client Connected")
         _ := websocket.JSON.Send(ws, msg);
    }
}

用上面的语法可以做到这一点吗? 如何调用带有附加参数的 Echoserver?

【问题讨论】:

标签: websocket go


【解决方案1】:

我假设你在这里想要的是一个一致的string 参数,它会为所有到 / 的连接返回。我使用了几种方法。 (这些特定的代码示例都没有经过测试;如果它们不编译,我可以提取一些真实的代码。)

一种是让数据成为接收者。我最常将它与结构一起使用,但任何参数都可以。这仅适用于单个参数(但您当然可以将多个参数放入一个结构中)。当参数是“类似对象”时,我喜欢这种方法。 (通常是一个结构,上面有其他方法。)

type echoStuff string

var hey echoStuff = "Hey!"

http.Handle("/", websocket.Handler(hey.EchoServer))
err := http.ListenAndServe(":8081", nil)
CheckError(err)

func (msg echoStuff) Echoserver(ws *websocket.Conn) {
  fmt.Println("Client Connected")
   _ := websocket.JSON.Send(ws, msg);
}

另一种方法是使用闭包。当参数是“类似数据”时,我喜欢这种方法。 (类似于字符串或其他简单数据。注意这种方法不需要创建本地类型。)

func WebSocketServer() {
  http.Handle("/", echoHandler("Hey!"))
  err := http.ListenAndServe(":8081", nil)
  CheckError(err)
}

func echoHandler(msg string) websocket.Handler {
  return func(ws *Conn) {
    Echoserver(ws, msg)
  }
}

【讨论】:

  • 这对我有用,谢谢!但是我用 golang 编写的服务器崩溃了。这是错误“golang panic: http: multiple registrations for /”
  • 这通常意味着您以/ 作为第一个参数多次调用http.Handle()
【解决方案2】:

您不应该以这种方式传递参数,因为 websocket.Handler 需要具有特定签名的函数。

func(*Conn)

这可能是需要频道的情况。
this example for instance:

首先,您的处理函数创建一个通道:

yourHandlerFunction := func(ws *websocket.Conn) {
  client := NewClient(ws, self)
  self.addClient <- client
  client.Listen()
  defer ws.Close()
}

(这里是一个"Client" is a struct,其中包括一个通道和一个指向websocket.Conn的指针)

然后服务器等待新的客户端,并以这种方式传递消息:

for {
  select {

    // Add new a client
    case c := <-self.addClient:
      log.Println("Added new client")
      self.clients = append(self.clients, c)
      for _, msg := range self.messages {
        c.Write() <- msg
    }

最后是Client can receive the message,然后进行 JSON 调用:

// Listen write request via chanel
func (self *Client) listenWrite() {
  log.Println("Listening write to client")
  for {
    select {

      // send message to the client
      case msg := <-self.ch:
        log.Println("Send:", msg)
        websocket.JSON.Send(self.ws, msg)

      // receive done request
      case <-self.done:
        self.server.RemoveClient() <- self
        self.done <- true // for listenRead method
      return
    }
  }
}

【讨论】:

    猜你喜欢
    • 2014-02-16
    • 2015-03-31
    • 2012-09-09
    • 2020-07-05
    • 1970-01-01
    • 2019-09-23
    • 2018-02-02
    • 2015-09-04
    • 1970-01-01
    相关资源
    最近更新 更多