github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/sync2/example/before.go (about) 1 package example 2 3 import ( 4 "io" 5 "sync" 6 ) 7 8 type ChannelBefore struct { 9 mu sync.Mutex 10 clients map[string]io.ReadWriter 11 } 12 13 func (channel *ChannelBefore) Connect(name string, client io.ReadWriter) { 14 channel.mu.Lock() 15 defer channel.mu.Unlock() 16 17 channel.broadcast(name + " connected") 18 channel.clients[name] = client 19 } 20 21 func (channel *ChannelBefore) Disconnect(name string) { 22 channel.mu.Lock() 23 defer channel.mu.Unlock() 24 channel.disconnect(name) 25 } 26 27 func (channel *ChannelBefore) disconnect(name string) { 28 // channel.mu must be held 29 delete(channel.clients, name) 30 channel.broadcast(name + " disconnected") 31 } 32 33 func (channel *ChannelBefore) broadcast(message string) { 34 // channel.mu must be held 35 for name, client := range channel.clients { 36 n, err := client.Write([]byte(message)) 37 if err != nil || n != len(message) { 38 channel.disconnect(name) 39 } 40 } 41 }