kaca消息发布/订阅系统
kaca 是用 golang 语言开发的基于 websocket 协议的消息发布/订阅系统。
服务器端代码:
package main import ( "github.com/scottkiss/kaca" ) func main() { //use true to set check origin kaca.ServeWs(":8080",true) }
发布订阅客户端:
package main import ( "fmt" "github.com/scottkiss/kaca" "time" ) func main() { producer := kaca.NewClient(":8080", "ws") consumer := kaca.NewClient(":8080", "ws") consumer.Sub("say") consumer.Sub("you") consumer.ConsumeMessage(func(message string) { fmt.Println("consume =>" + message) }) time.Sleep(time.Second * time.Duration(2)) producer.Pub("you", "world") producer.Pub("say", "hello") time.Sleep(time.Second * time.Duration(2)) }
广播客户端:
package main import ( "fmt" "github.com/scottkiss/kaca" "time" ) func main() { producer := kaca.NewClient(":8080", "ws") consumer := kaca.NewClient(":8080", "ws") c2 := kaca.NewClient(":8080", "ws") c2.ConsumeMessage(func(message string) { fmt.Println("c2 consume =>" + message) }) consumer.Sub("say") consumer.Sub("you") consumer.ConsumeMessage(func(message string) { fmt.Println("consume =>" + message) }) time.Sleep(time.Second * time.Duration(2)) producer.Broadcast("broadcast...") time.Sleep(time.Second * time.Duration(2)) }) }
评论