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