Created
January 31, 2019 08:48
-
-
Save kelindar/0b2e3510d4cdd90d7de9f659e74e2b42 to your computer and use it in GitHub Desktop.
Emitter: Golang Client-Server using Emitter Links
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "time" | |
| emitter "github.com/emitter-io/go" | |
| ) | |
| // demo license: zT83oDV0DWY5_JysbSTPTDr8KB0AAAAAAAAAAAAAAAI | |
| // demo secret key: kBCZch5re3Ue-kpG1Aa8Vo7BYvXZ3UwR | |
| func main() { | |
| server() | |
| client() | |
| // stop after 2 seconds | |
| time.Sleep(2 * time.Second) | |
| } | |
| func server() { | |
| const key = "cmSaSPPzVcq4LsmmEzYjyPIH1JUC5r3S" // read and write on demo/#/ | |
| // Create client options | |
| o := emitter.NewClientOptions() | |
| o.AddBroker("tcp://127.0.0.1:8080") | |
| o.SetOnMessageHandler(func(c emitter.Emitter, msg emitter.Message) { | |
| fmt.Printf("[emitter] -> [A] received: '%s' topic: '%s'\n", msg.Payload(), msg.Topic()) | |
| }) | |
| // Create a new emitter client and connect to the broker | |
| c := emitter.NewClient(o) | |
| c.Connect().WaitTimeout(time.Second) | |
| // Subscribe to demo channel | |
| fmt.Println("[emitter] <- [A] subscribing to 'demo/...'") | |
| c.Subscribe(key, "demo/").WaitTimeout(time.Second) | |
| } | |
| func client() { | |
| const key = "tGxkIMapzyQx5Cc7koX5NVtQV7tA8tMw" // everything on demo/ | |
| // Create the options with default values | |
| o := emitter.NewClientOptions() | |
| o.AddBroker("tcp://127.0.0.1:8080") | |
| // Set the message handler | |
| o.SetOnMessageHandler(func(_ emitter.Emitter, msg emitter.Message) { | |
| fmt.Printf("[emitter] -> [B] received: '%s' topic: '%s'\n", msg.Payload(), msg.Topic()) | |
| }) | |
| // Set the link notification handler | |
| o.SetOnLinkHandler(func(_ emitter.Emitter, p emitter.LinkResponse) { | |
| fmt.Printf("[emitter] -> [B] created private link '%v' for '%v'\n", p.Name, p.Channel) | |
| }) | |
| // Create a new emitter client and connect to the broker | |
| c := emitter.NewClient(o) | |
| c.Connect().WaitTimeout(time.Second) | |
| // Ask to create a private link | |
| fmt.Println("[emitter] <- [B] creating a private link") | |
| c.CreatePrivateLink(key, "demo/", "1", true).WaitTimeout(time.Second) | |
| // Publish to the private link | |
| fmt.Println("[emitter] <- [B] publishing to private link") | |
| c.PublishWithLink("1", "hi from private link").WaitTimeout(time.Second) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment