A simple net.Conn multiplexer based on named topics & channels. Subscribing to a topic returns a channel on which updates will be sent.
func dialer() {
// ignore the errors for brevity (it's an example)
conn, _ := net.Dial("unix", "/tmp/example")
// implement chamux.Serializer to use another
mc := chamux.NewMConn(conn, chamux.Gob{}, chamux.Options{})
// get a channel for a topic named: coffee
topic := chamux.NewTopic("coffee")
subscription := topic.Subscribe()
mc.AddTopic(&topic)
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
loop:
for {
select {
case <-sigint:
mc.Close()
break loop
case msg := <-subscription:
log.Println("something about coffee:", string(msg))
}
}
func listener() {
listener, _ := net.Listen("unix", "/tmp/example")
for {
conn, _ := listener.Accept()
mc := chamux.NewMConn(conn, chamux.Gob{}, chamux.Options{})
// send lots of messages about coffee
go func(chamux.MConn) {
for {
msg := []byte("we need more coffee")
frame := chamux.NewFrame(msg, "coffee")
mc.Publish(frame)
}
}(mc)
}
}
This package exports Gob{}
. If you want to use another encoding, simply implement Serializer
.
type Serializer interface {
Serialize(f *Frame) ([]byte, error)
Deserialize(f []byte) (*Frame, error)
}