我正在尝试使用websockets向客户端发送广播消息。如何修复此代码以正确地向所有客户端发送消息并且没有该错误?
package main
import (
"fmt"
"golang.org/x/net/websocket"
"net/http"
)
var connections []websocket.Conn
func main() {
fmt.Println("vim-go")
http.Handle("/", websocket.Handler(Server))
err := http.ListenAndServe(":8888", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
func Server(ws *websocket.Conn) {
lll := append(connections, *ws)
var message string
websocket.Message.Receive(ws, &message)
fmt.Println(message)
for ccc := range connections {
websocket.Message.Send(ccc, "Another connection!!!")
}
}
答案 0 :(得分:1)
不确定您要对lll
尝试做什么,但不使用它,您的代码不应该是事件编译。
当range
在:=
左侧使用单次迭代变量对{/ 1}进行切片/数组时,将为其分配迭代索引。因此,在您的情况下,ccc
是索引。
你可以做的一件事是:
for ccc := range connections {
websocket.Message.Send(connections[ccc], "Another connection!!!")
}
但你可能真正想要的是,删除索引并立即获取元素你可以使用两个迭代变量,_
作为第一个,如果你没有使用索引在所有
for _, ccc := range connections {
websocket.Message.Send(ccc, "Another connection!!!")
}
在此处阅读更多内容:https://golang.org/ref/spec#For_range