1 回答

TA貢獻1799條經(jīng)驗 獲得超6個贊
與通道發(fā)送方通信
如前所述,通道的通道是一種直接響應(yīng)通道發(fā)送方的方法。下面是一個示例:
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
}
至于關(guān)于識別特定發(fā)送者的第二個問題,你可以使用像goroutinemap這樣的東西,它允許你管理命名的go-routines的生命周期。但是,這種模式并不常見,如果您需要識別特定的通道發(fā)送方,則可以(并且應(yīng)該)重新設(shè)計解決方案。
管理應(yīng)用程序狀態(tài)
這完全取決于您的應(yīng)用程序及其功能。編輯:根據(jù)OP的說法,該應(yīng)用程序是websockets上的國際象棋游戲。您可以考慮創(chuàng)建一個數(shù)據(jù)結(jié)構(gòu),其中包含對玩家的 websocket 連接以及玩家之間的游戲狀態(tài)的引用。這種數(shù)據(jù)結(jié)構(gòu)將在游戲啟動時創(chuàng)建,然后數(shù)據(jù)結(jié)構(gòu)可以管理玩家之間的來回消息以及內(nèi)部游戲狀態(tài)的更新。也許像這樣的東西
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 關(guān)注
- 85 瀏覽
添加回答
舉報