英文:
cannot use ccc (type int) as type *websocket.Conn in argument to websocket.Message.Send
问题
我正在尝试使用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) {
connections = append(connections, *ws)
var message string
websocket.Message.Receive(ws, &message)
fmt.Println(message)
for _, ccc := range connections {
websocket.Message.Send(&ccc, "Another connection!!!")
}
}
这段代码存在几个问题。首先,connections
变量应该是一个指向websocket.Conn
的切片,而不是websocket.Conn
的切片。所以,你需要将connections
的类型更改为[]*websocket.Conn
。
其次,在Server
函数中,你应该使用range
关键字来遍历connections
切片,而不是使用range
关键字的索引。这样可以直接获取到每个连接。
最后,在发送消息时,你应该使用连接的指针作为参数,而不是连接本身。所以,你需要将websocket.Message.Send(ccc, "Another connection!!!")
更改为websocket.Message.Send(&ccc, "Another connection!!!")
。
修复后的代码如上所示。希望能帮到你!
英文:
I am trying to send a broadcast message to clients using websockets. How to fix this code to send message properly to all clients and without that error?
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!!!")
}
}
答案1
得分: 1
不确定你在使用lll
时想要做什么,但是如果不使用它,你的代码应该无法编译。
当在:=
的左侧使用单个迭代变量对切片/数组进行迭代时,它将被赋予迭代的索引。所以在你的例子中,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
英文:
Not sure what you're trying to do with lll
but without using it your code should not event compile.
When range
ing over slices/arrays with a single iteration variable on the left of :=
it will be assigned the index of the iteration. So in your case ccc
is the index.
One thing you can do is:
for ccc := range connections {
websocket.Message.Send(connections[ccc], "Another connection!!!")
}
But what you probably really want is, drop the index and get the element right away which you can do using two iteration variables with the _
as the first one if you don't inted to use the index at all.
for _, ccc := range connections {
websocket.Message.Send(ccc, "Another connection!!!")
}
read more here: https://golang.org/ref/spec#For_range
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论