How to broadcast message using channel

后端 未结 6 1801
粉色の甜心
粉色の甜心 2020-11-27 14:04

I am new to go and I am trying to create a simple chat server where clients can broadcast messages to all connected clients.

In my server, I have a goroutine (infin

6条回答
  •  醉话见心
    2020-11-27 14:37

    Because Go channels follow the Communicating Sequential Processes (CSP) pattern, channels are a point-to-point communication entity. There is always one writer and one reader involved in each exchange.

    However, each channel end can be shared amongst multiple goroutines. This is safe to do - there is no dangerous race condition.

    So there can be multiple writers sharing the writing end. And/or there can be multiple readers sharing the reading end. I wrote more on this in a different answer, which includes examples.

    If you really need a broadcast, you cannot do this directly, but it is not hard to implement an intermediate goroutine that copies a value out to each of a group of output channels.

提交回复
热议问题