亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何回復通道的發送方和管理狀態

如何回復通道的發送方和管理狀態

Go
慕的地8271018 2022-09-05 16:45:58
我想知道如何直接回復Go中頻道的發件人。更有趣的是如何識別發件人以供以后使用。我正在將其與Elixir GenServer進行比較,在那里我可以直接回復發件人或向所有人廣播。Go 中是否缺少此功能?無論我在Go中讀到有關頻道的任何地方,我都找不到如何做到這一點。此外,在Elixir保持狀態下的GenServers變成了一個無限運行的過程。圍棋的賽法是否類似于保持和通過狀態?如果不是,這是如何實現的?
查看完整描述

1 回答

?
哈士奇WWW

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

}


查看完整回答
反對 回復 2022-09-05
  • 1 回答
  • 0 關注
  • 86 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號