Skip to content

Instantly share code, notes, and snippets.

@taotetek
Created May 24, 2015 16:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taotetek/9906323e701b113d2630 to your computer and use it in GitHub Desktop.
Save taotetek/9906323e701b113d2630 to your computer and use it in GitHub Desktop.
ReadWriter support in goczmq
package main
import (
"encoding/gob"
"fmt"
"github.com/zeromq/goczmq"
)
// person is an example type we will encode, send, and decode
type person struct {
Firstname string
Lastname string
Age int
}
func main() {
// First, we make a push socket with a czmq "smart" constructor.
// The "@" tells the constructor to bind.
push, err := goczmq.NewPush("@tcp://*:5555")
if err != nil {
panic(err)
}
defer push.Destroy()
// Now, let's make an encoder that will encode to this socket.
encoder := gob.NewEncoder(push)
// Next, we make a pull socket.
// The ">" tells the socket to connect.
pull, err := goczmq.NewPull(">tcp://127.0.0.1:5555")
if err != nil {
panic(err)
}
defer pull.Destroy()
// Now, let's make a decoder that will decode from this socket.
decoder := gob.NewDecoder(pull)
// Send an encoded type.
err = encoder.Encode(person{
Firstname: "Arthur",
Lastname: "Dent",
Age: 30})
if err != nil {
panic(err)
}
// Receive the message and decode it.
var p person
err = decoder.Decode(&p)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", p)
}
@bryanl
Copy link

bryanl commented May 24, 2015

The only potential weirdness I see here is that line 52 may block for some indeterminate amount of time. It's not an error, but offends the asynchronous developer in me.

@taotetek
Copy link
Author

@bryanl in a "real" scenario, I'd use a poller on the socket and then only call decode if there was a message waiting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment