2017-08-26 138 views
2

我試圖使用websockets向客戶端發送廣播消息。如何解決這段代碼將消息正確地發送給所有客戶端並且沒有該錯誤?不能使用ccc(類型爲int)作爲類型* websocket.Conn在websocket.Message.Send的參數中

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

不知道你想什麼用lll做,但沒有使用它你的代碼不應該編譯事件。


range ING超過切片/陣列與單次迭代上的:=左側變量將分配給在迭代的索引。所以在你的情況下,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

相關問題