登录
首页 >  Golang >  Go问答

回复频道发送者并控制状态

来源:stackoverflow

时间:2024-03-08 16:30:25 342浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《回复频道发送者并控制状态》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我想知道如何在 Go 中直接回复频道的发送者。更有趣的是如何识别发件人以供以后使用。

我将其与 Elixir GenServer 进行比较,在 Elixir GenServer 中我可以直接回复发件人或向所有人广播。 Go 中缺少此功能吗?

在我读到有关 Go 中通道的所有地方,我都找不到如何做到这一点。

此外,Elixir 中的 GenServer 保持状态,使其成为无限运行的进程。 Go有类似hold和pass状态的东西吗?如果不是,这是如何实现的?


正确答案


与频道发送者通信

正如已经提到的,channel of channels 是直接响应频道发送者的一种方式。这是一个例子:

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 例程的生命周期。然而,这种模式并不常见,如果您需要识别特定的渠道发送者,您可能(并且应该)重新设计您的解决方案。

管理应用程序状态

这完全取决于您的应用程序及其用途。编辑:根据 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
}

本篇关于《回复频道发送者并控制状态》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>