1 回答

TA貢獻1799條經驗 獲得超6個贊
與通道發送方通信
如前所述,通道的通道是一種直接響應通道發送方的方法。下面是一個示例:
package main
func main() {
// Make a communication channel by creating a channel of channels
c := make(chan chan struct{})
// Start a sender with the communication channel
go sender(c)
// Receive a message from the sender, in this case the message is a channel itself
r := <- c
// Send response to the sender on the channel given to us by the sender
r <- struct{}{}
}
func sender(c chan chan struct{}) {
// Create a channel the receiver will use to respond to us
r := make(chan struct{})
// Send the channel to the receiver
c <- r
// This is the response received after the received got the message
<- r
}
至于關于識別特定發送者的第二個問題,你可以使用像goroutinemap這樣的東西,它允許你管理命名的go-routines的生命周期。但是,這種模式并不常見,如果您需要識別特定的通道發送方,則可以(并且應該)重新設計解決方案。
管理應用程序狀態
這完全取決于您的應用程序及其功能。編輯:根據OP的說法,該應用程序是websockets上的國際象棋游戲。您可以考慮創建一個數據結構,其中包含對玩家的 websocket 連接以及玩家之間的游戲狀態的引用。這種數據結構將在游戲啟動時創建,然后數據結構可以管理玩家之間的來回消息以及內部游戲狀態的更新。也許像這樣的東西
type GameState struct {
Player1 *websocket.Conn
Player2 *websocket.Conn
// Add any game state needed here
}
func (s *GameState) run(ctx context.Context) {
// Send messages between websocket connections here and update game state accordingly
}
- 1 回答
- 0 關注
- 86 瀏覽
添加回答
舉報