Documentation ¶
Overview ¶
Package messenger provides a simple broadcasting mechanism
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Messenger ¶
type Messenger struct {
// contains filtered or unexported fields
}
Messenger instance. Must be invoked with New().
func New ¶
New creates a new Messenger instance.
Buffer sets the buffer size to client channels, set to 0 if you want unbuffered behaviour.
Drop makes broadcasts to drop if a client's buffer is full. Ignored with 0 buffer size.
Example ¶
package main import ( "fmt" "log" "sync" "time" "github.com/ugjka/messenger" ) func main() { log.SetFlags(log.Lmicroseconds) log.SetPrefix("time ") m := messenger.New(0, false) wg := &sync.WaitGroup{} for i := 1; i <= 5; i++ { wg.Add(1) go func(i int, m *messenger.Messenger) { defer wg.Done() time.Sleep(time.Millisecond * time.Duration(i*20)) client, err := m.Sub() if err != nil { log.Printf("Client %d: %v\n", i, err) return } log.Printf("Client %d subscribed\n", i) timeout := time.After(time.Millisecond * time.Duration(i*100)) for { select { case msg := <-client: log.Printf("Client %d got message: %s\n", i, msg) case <-timeout: m.Unsub(client) log.Printf("Client %d unsubscribed\n", i) return } } }(i, m) } for i := 0; i < 10; i++ { time.Sleep(time.Millisecond * 50) m.Broadcast(fmt.Sprintf("nr.%d", i)) } wg.Wait() }
Output:
func (*Messenger) Broadcast ¶
func (m *Messenger) Broadcast(msg interface{})
Broadcast broadcasts a message to all current clients. If a client is not listening and drop is not set this will block.
func (*Messenger) Kill ¶
func (m *Messenger) Kill()
Kill closes and removes all clients and stops the monitor() goroutine of Messenger, making the Messenger instance unusable. Kill should only be called when all clients have exited.
Click to show internal directories.
Click to hide internal directories.