第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何回復(fù)通道的發(fā)送方和管理狀態(tài)

如何回復(fù)通道的發(fā)送方和管理狀態(tài)

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

1 回答

?
哈士奇WWW

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

}


查看完整回答
反對 回復(fù) 2022-09-05
  • 1 回答
  • 0 關(guān)注
  • 85 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號