func main() { // Socket to receive messages on receiver := goczmq.NewSock(goczmq.Pull) defer receiver.Destroy() receiver.Connect("tcp://localhost:5557") // Socket to send messages to task sink sender := goczmq.NewSock(goczmq.Push) defer sender.Destroy() sender.Connect("tcp://localhost:5558") // Process tasks forever for { msgbytes, _ := receiver.RecvMessage() fmt.Printf("%s.\n", string(msgbytes[0])) // Do the work msec, _ := strconv.ParseInt(string(msgbytes[0]), 10, 64) time.Sleep(time.Duration(msec) * 1e6) // Send results to sink sender.SendMessage([][]byte{[]byte("")}) } }
func main() { var messageSize = flag.Int("message_size", 0, "size of message") var messageCount = flag.Int("message_count", 0, "number of messages") flag.Parse() pullSock := czmq.NewSock(czmq.Pull) defer pullSock.Destroy() _, err := pullSock.Bind("inproc://test") if err != nil { panic(err) } go func() { pushSock := czmq.NewSock(czmq.Push) defer pushSock.Destroy() err := pushSock.Connect("inproc://test") if err != nil { panic(err) } for i := 0; i < *messageCount; i++ { payload := make([]byte, *messageSize) err = pushSock.SendFrame(payload, 0) if err != nil { panic(err) } } }() startTime := time.Now() for i := 0; i < *messageCount; i++ { msg, _, err := pullSock.RecvFrame() if err != nil { panic(err) } if len(msg) != *messageSize { panic("msg too small") } } endTime := time.Now() elapsed := endTime.Sub(startTime) throughput := float64(*messageCount) / elapsed.Seconds() megabits := float64(throughput*float64(*messageSize)*8.0) / 1e6 log.Printf("message size: %d", *messageSize) log.Printf("message count: %d", *messageCount) log.Printf("test time (seconds): %f", elapsed.Seconds()) log.Printf("mean throughput: %f [msg/s]", throughput) log.Printf("mean throughput: %f [Mb/s]", megabits) }
func main() { // Socket to receive messages on receiver := goczmq.NewSock(goczmq.Pull) defer receiver.Destroy() receiver.Bind("tcp://*:5558") // Wait for start of batch msgbytes, _ := receiver.RecvMessage() fmt.Println("Received Start Msg ", string(msgbytes[0])) // Start our clock now start_time := time.Now().UnixNano() // Process 100 confirmations for i := 0; i < 100; i++ { msgbytes, _ = receiver.RecvMessage() fmt.Print(".") } // Calculate and report duration of batch te := time.Now().UnixNano() fmt.Printf("Total elapsed time: %d msec\n", (te-start_time)/1e6) }
func main() { socket := goczmq.NewSock(goczmq.Sub) defer socket.Destroy() var temps []string var err error var temp int64 total_temp := 0 filter := "59937" // find zipcode if len(os.Args) > 1 { // ./wuclient 85678 filter = string(os.Args[1]) } // Subscribe to just one zipcode (whitefish MT 59937) fmt.Printf("Collecting updates from weather server for %s…\n", filter) socket.SetSubscribe(filter) socket.Connect("tcp://localhost:5556") for i := 0; i < 101; i++ { // found temperature point datapt, _ := socket.RecvMessage() temps = strings.Split(string(datapt[0]), " ") temp, err = strconv.ParseInt(temps[1], 10, 64) if err == nil { // Invalid string total_temp += int(temp) } } fmt.Printf("Average temperature for zipcode %s was %dF \n\n", filter, total_temp/100) }
func main() { // Socket to send messages On sender := goczmq.NewSock(goczmq.Push) defer sender.Destroy() sender.Bind("tcp://*:5557") // Socket to send start of batch message on sink := goczmq.NewSock(goczmq.Push) defer sink.Destroy() sink.Connect("tcp://localhost:5558") fmt.Print("Press Enter when the workers are ready: ") var line string fmt.Scanln(&line) fmt.Println("Sending tasks to workers…") sink.SendMessage([][]byte{[]byte("0")}) // Seed the random number generator rand.Seed(time.Now().UnixNano()) total_msec := 0 for i := 0; i < 100; i++ { workload := rand.Intn(100) total_msec += workload msg := []byte(fmt.Sprintf("%d", workload)) sender.SendMessage([][]byte{msg}) } fmt.Printf("Total expected cost: %d msec\n", total_msec) time.Sleep(1e9) // Give 0MQ time to deliver: one second == 1e9 ns }
func main() { socket := goczmq.NewSock(goczmq.Req) defer socket.Destroy() fmt.Printf("Connecting to hello world server...") socket.Connect("tcp://localhost:5555") for i := 0; i < 10; i++ { // send hello msg := []byte(fmt.Sprintf("Hello %d", i)) socket.SendMessage([][]byte{msg}) println("Sending ", string(msg)) // Wait for reply: reply, _ := socket.RecvMessage() println("Received ", string(reply[0])) } }
func main() { socket := goczmq.NewSock(goczmq.Rep) defer socket.Destroy() socket.Bind("tcp://*:5555") // Wait for messages for { msg, _ := socket.RecvMessage() println("Received ", string(msg[0])) // do some fake "work" time.Sleep(time.Second) // send reply back to client reply := []byte("World") socket.SendMessage([][]byte{reply}) } }
func Setup() { config := config.Read() broadcastUri := fmt.Sprintf("tcp://%s:%d", config.Broadcaster.Host, config.Broadcaster.Port) var err error broadcaster, err = goczmq.NewPub(broadcastUri) if err != nil { panic(err) } log.Println("Broadcaster will start on", broadcastUri) pitcher = goczmq.NewSock(goczmq.Push) receiver, err = goczmq.NewPull("inproc://broadcast") if err != nil { panic(err) } helpers.ConnectToPeers(true, ConnectToBroadcatcher) }
func main() { socket := goczmq.NewSock(goczmq.Pub) defer socket.Destroy() socket.Bind("tcp://*:5556") socket.Bind("ipc://weather.ipc") // Seed the random number generator rand.Seed(time.Now().UnixNano()) // loop for a while aparently for { // make values that will fool the boss zipcode := rand.Intn(100000) temperature := rand.Intn(215) - 80 relhumidity := rand.Intn(50) + 10 msg := []byte(fmt.Sprintf("%d %d %d", zipcode, temperature, relhumidity)) // Send message to all subscribers socket.SendMessage([][]byte{msg}) } }
// Yay! Test function. func TestTypes(t *testing.T) { var ( sndMsg []byte rcvMsg []byte rcvDigest string sndDigest string ) // Create pair of sockets we can send through // Output socket output := goczmq.NewSock(goczmq.Dealer) defer output.Destroy() routingID := "Shout" output.SetIdentity(routingID) _, err := output.Bind("inproc://selftest-types") if err != nil { t.Fatal(err) } defer output.Unbind("inproc://selftest-types") // Input socket input := goczmq.NewSock(goczmq.Router) defer input.Destroy() err = input.Connect("inproc://selftest-types") if err != nil { t.Fatal(err) } defer input.Disconnect("inproc://selftest-types") // Create a Types message and send it through the wire types := NewTypes() types.sequence = 123 types.ClientForename = "Lucius Junius" types.ClientSurname = "Brutus" types.ClientMobile = "01234567890" types.ClientEmail = "*****@*****.**" types.SupplierForename = "Leslie" types.SupplierSurname = "Lamport" types.SupplierMobile = "01987654321" types.SupplierEmail = "*****@*****.**" err = types.Send(output) if err != nil { t.Fatal(err) } sndMsg, err = types.Marshal() if err != nil { t.Fatal(err) } sndDigest = fmt.Sprintf("%x", sha1.Sum(sndMsg)) if "dee674a1bcac455b7cd1801f4008c65d0a37b2ea" != sndDigest { fmt.Printf("sndMsg: %x\n", sndMsg) t.Fatalf("expected %q digest for types, got %s", "dee674a1bcac455b7cd1801f4008c65d0a37b2ea", sndDigest) } transit, err := Recv(input) if err != nil { t.Fatal(err) } tr := transit.(*Types) rcvMsg, err = tr.Marshal() if err != nil { t.Fatal(err) } rcvDigest = fmt.Sprintf("%x", sha1.Sum(rcvMsg)) if sndDigest != rcvDigest { fmt.Printf("sndMsg: %x\n", sndMsg) fmt.Printf("rcvMsg: %x\n", rcvMsg) t.Fatalf("inconsistent digest after sending and after receiving msg: %q != %q", sndDigest, rcvDigest) } if "dee674a1bcac455b7cd1801f4008c65d0a37b2ea" != rcvDigest { t.Fatalf("expected %q digest for types, got %s", "dee674a1bcac455b7cd1801f4008c65d0a37b2ea", rcvDigest) } // Tests number if tr.sequence != 123 { t.Fatalf("expected %d, got %d", 123, tr.sequence) } // Tests string if tr.ClientForename != "Lucius Junius" { t.Fatalf("expected %s, got %s", "Lucius Junius", tr.ClientForename) } // Tests string if tr.ClientSurname != "Brutus" { t.Fatalf("expected %s, got %s", "Brutus", tr.ClientSurname) } // Tests string if tr.ClientMobile != "01234567890" { t.Fatalf("expected %s, got %s", "01234567890", tr.ClientMobile) } // Tests string if tr.ClientEmail != "*****@*****.**" { t.Fatalf("expected %s, got %s", "*****@*****.**", tr.ClientEmail) } // Tests string if tr.SupplierForename != "Leslie" { t.Fatalf("expected %s, got %s", "Leslie", tr.SupplierForename) } // Tests string if tr.SupplierSurname != "Lamport" { t.Fatalf("expected %s, got %s", "Lamport", tr.SupplierSurname) } // Tests string if tr.SupplierMobile != "01987654321" { t.Fatalf("expected %s, got %s", "01987654321", tr.SupplierMobile) } // Tests string if tr.SupplierEmail != "*****@*****.**" { t.Fatalf("expected %s, got %s", "*****@*****.**", tr.SupplierEmail) } err = tr.Send(input) if err != nil { t.Fatal(err) } transit, err = Recv(output) if err != nil { t.Fatal(err) } if routingID != string(tr.RoutingID()) { t.Fatalf("expected %s, got %s", routingID, string(tr.RoutingID())) } }
func TestNew(t *testing.T) { endpoints := []string{"inproc://test1"} topics := []string{"topic1", "topic2"} servercert := "./example_certs/example_curve_server_cert" clientcert := "./example_certs/example_curve_client_cert" auth := goczmq.NewAuth() defer auth.Destroy() clientCert, err := goczmq.NewCertFromFile(clientcert) if err != nil { t.Fatal(err) } defer clientCert.Destroy() server := goczmq.NewSock(goczmq.Pub) defer server.Destroy() server.SetZapDomain("global") serverCert, err := goczmq.NewCertFromFile(servercert) defer serverCert.Destroy() if err != nil { t.Fatal(err) } serverCert.Apply(server) server.SetCurveServer(1) err = auth.Curve("./example_certs/") if err != nil { t.Fatal(err) } server.Bind(endpoints[0]) lt, err := New(endpoints, topics, servercert, clientcert) if err != nil { t.Errorf("NewLogTalez failed: %s", err) } server.SendFrame([]byte("topic1:hello world"), 0) buf := make([]byte, 65536) n, err := lt.Read(buf) if err != nil { t.Errorf("expected nil, got %s", err) } if string(buf[:n]) != "topic1:hello world" { t.Errorf("expected 'topic1:hello world', got '%s'", buf[:n]) } server.SendFrame([]byte("topic2:hello again"), 0) n, err = lt.Read(buf) if err != nil { t.Errorf("expected nil, got %s", err) } if string(buf[:n]) != "topic2:hello again" { t.Errorf("expected 'topic2:hello again', got '%s'", buf[:n]) } }
// Yay! Test function. func TestLog(t *testing.T) { var ( sndMsg []byte rcvMsg []byte rcvDigest string sndDigest string ) // Create pair of sockets we can send through // Output socket output := goczmq.NewSock(goczmq.Dealer) defer output.Destroy() routingID := "Shout" output.SetIdentity(routingID) _, err := output.Bind("inproc://selftest-log") if err != nil { t.Fatal(err) } defer output.Unbind("inproc://selftest-log") // Input socket input := goczmq.NewSock(goczmq.Router) defer input.Destroy() err = input.Connect("inproc://selftest-log") if err != nil { t.Fatal(err) } defer input.Disconnect("inproc://selftest-log") // Create a Log message and send it through the wire log := NewLog() log.sequence = 123 log.Level = 2 log.Event = 3 log.Node = 45536 log.Peer = 65535 log.Time = 1427261426 log.Host = "localhost" log.Data = "This is the message to log" err = log.Send(output) if err != nil { t.Fatal(err) } sndMsg, err = log.Marshal() if err != nil { t.Fatal(err) } sndDigest = fmt.Sprintf("%x", sha1.Sum(sndMsg)) if "b90f4926d4662b319c0ec113794b0f27d9336a23" != sndDigest { fmt.Printf("sndMsg: %x\n", sndMsg) t.Fatalf("expected %q digest for log, got %s", "b90f4926d4662b319c0ec113794b0f27d9336a23", sndDigest) } transit, err := Recv(input) if err != nil { t.Fatal(err) } tr := transit.(*Log) rcvMsg, err = tr.Marshal() if err != nil { t.Fatal(err) } rcvDigest = fmt.Sprintf("%x", sha1.Sum(rcvMsg)) if sndDigest != rcvDigest { fmt.Printf("sndMsg: %x\n", sndMsg) fmt.Printf("rcvMsg: %x\n", rcvMsg) t.Fatalf("inconsistent digest after sending and after receiving msg: %q != %q", sndDigest, rcvDigest) } if "b90f4926d4662b319c0ec113794b0f27d9336a23" != rcvDigest { t.Fatalf("expected %q digest for log, got %s", "b90f4926d4662b319c0ec113794b0f27d9336a23", rcvDigest) } // Tests number if tr.sequence != 123 { t.Fatalf("expected %d, got %d", 123, tr.sequence) } // Tests number if tr.Level != 2 { t.Fatalf("expected %d, got %d", 2, tr.Level) } // Tests number if tr.Event != 3 { t.Fatalf("expected %d, got %d", 3, tr.Event) } // Tests number if tr.Node != 45536 { t.Fatalf("expected %d, got %d", 45536, tr.Node) } // Tests number if tr.Peer != 65535 { t.Fatalf("expected %d, got %d", 65535, tr.Peer) } // Tests number if tr.Time != 1427261426 { t.Fatalf("expected %d, got %d", 1427261426, tr.Time) } // Tests string if tr.Host != "localhost" { t.Fatalf("expected %s, got %s", "localhost", tr.Host) } // Tests longstr if tr.Data != "This is the message to log" { t.Fatalf("expected %s, got %s", "This is the message to log", tr.Data) } err = tr.Send(input) if err != nil { t.Fatal(err) } transit, err = Recv(output) if err != nil { t.Fatal(err) } if routingID != string(tr.RoutingID()) { t.Fatalf("expected %s, got %s", routingID, string(tr.RoutingID())) } }
// Yay! Test function. func TestBinary(t *testing.T) { var ( sndMsg []byte rcvMsg []byte rcvDigest string sndDigest string ) // Create pair of sockets we can send through // Output socket output := goczmq.NewSock(goczmq.Dealer) defer output.Destroy() routingID := "Shout" output.SetIdentity(routingID) _, err := output.Bind("inproc://selftest-binary") if err != nil { t.Fatal(err) } defer output.Unbind("inproc://selftest-binary") // Input socket input := goczmq.NewSock(goczmq.Router) defer input.Destroy() err = input.Connect("inproc://selftest-binary") if err != nil { t.Fatal(err) } defer input.Disconnect("inproc://selftest-binary") // Create a Binary message and send it through the wire binary := NewBinary() binary.sequence = 123 binary.Flags = []byte("b38c") binary.PublicKey = []byte("89f5ffe70d747869dfe8") binary.Identifier, _ = hex.DecodeString("3a60e6850a1e4cc15f3bfd4b42bc6b3e") binary.Address = []byte("0206f99f6137d9fe380f") binary.Content = []byte("728a92c6749235ba7002") err = binary.Send(output) if err != nil { t.Fatal(err) } sndMsg, err = binary.Marshal() if err != nil { t.Fatal(err) } sndDigest = fmt.Sprintf("%x", sha1.Sum(sndMsg)) if "740caf04158436b4a81b844135a8a1dc9e4f8a54" != sndDigest { fmt.Printf("sndMsg: %x\n", sndMsg) t.Fatalf("expected %q digest for binary, got %s", "740caf04158436b4a81b844135a8a1dc9e4f8a54", sndDigest) } transit, err := Recv(input) if err != nil { t.Fatal(err) } tr := transit.(*Binary) rcvMsg, err = tr.Marshal() if err != nil { t.Fatal(err) } rcvDigest = fmt.Sprintf("%x", sha1.Sum(rcvMsg)) if sndDigest != rcvDigest { fmt.Printf("sndMsg: %x\n", sndMsg) fmt.Printf("rcvMsg: %x\n", rcvMsg) t.Fatalf("inconsistent digest after sending and after receiving msg: %q != %q", sndDigest, rcvDigest) } if "740caf04158436b4a81b844135a8a1dc9e4f8a54" != rcvDigest { t.Fatalf("expected %q digest for binary, got %s", "740caf04158436b4a81b844135a8a1dc9e4f8a54", rcvDigest) } // Tests number if tr.sequence != 123 { t.Fatalf("expected %d, got %d", 123, tr.sequence) } // Tests octets if len(tr.Flags) != 4 { t.Fatalf("mismatch octets size for %s", "Flags") } for idx, b := range []byte("b38c") { if tr.Flags[idx] != b { t.Fatalf("mismatch octets value for %s", "Flags") } } // Tests chunk if string(tr.PublicKey) != "89f5ffe70d747869dfe8" { t.Fatalf("expected %s, got %s", "89f5ffe70d747869dfe8", tr.PublicKey) } // Tests uuid if hex.EncodeToString(tr.Identifier) != "3a60e6850a1e4cc15f3bfd4b42bc6b3e" { t.Fatalf("expected %s, got %s", "3a60e6850a1e4cc15f3bfd4b42bc6b3e", tr.Identifier) } // Tests frame if string(tr.Address) != "0206f99f6137d9fe380f" { t.Fatalf("expected %s, got %s", "0206f99f6137d9fe380f", tr.Address) } // Tests msg if string(tr.Content) != "728a92c6749235ba7002" { t.Fatalf("expected %s, got %s", "728a92c6749235ba7002", tr.Content) } err = tr.Send(input) if err != nil { t.Fatal(err) } transit, err = Recv(output) if err != nil { t.Fatal(err) } if routingID != string(tr.RoutingID()) { t.Fatalf("expected %s, got %s", routingID, string(tr.RoutingID())) } }
// Yay! Test function. func TestStructures(t *testing.T) { var ( sndMsg []byte rcvMsg []byte rcvDigest string sndDigest string ) // Create pair of sockets we can send through // Output socket output := goczmq.NewSock(goczmq.Dealer) defer output.Destroy() routingID := "Shout" output.SetIdentity(routingID) _, err := output.Bind("inproc://selftest-structures") if err != nil { t.Fatal(err) } defer output.Unbind("inproc://selftest-structures") // Input socket input := goczmq.NewSock(goczmq.Router) defer input.Destroy() err = input.Connect("inproc://selftest-structures") if err != nil { t.Fatal(err) } defer input.Disconnect("inproc://selftest-structures") // Create a Structures message and send it through the wire structures := NewStructures() structures.sequence = 123 structures.Aliases = []string{ "First alias", "Second alias", "Third alias", } structures.Headers = map[string]string{"endpoint": "tcp://localhost:5665"} err = structures.Send(output) if err != nil { t.Fatal(err) } sndMsg, err = structures.Marshal() if err != nil { t.Fatal(err) } sndDigest = fmt.Sprintf("%x", sha1.Sum(sndMsg)) if "52d9e295862bc3edad2841c412327a50d2c1b857" != sndDigest { fmt.Printf("sndMsg: %x\n", sndMsg) t.Fatalf("expected %q digest for structures, got %s", "52d9e295862bc3edad2841c412327a50d2c1b857", sndDigest) } transit, err := Recv(input) if err != nil { t.Fatal(err) } tr := transit.(*Structures) rcvMsg, err = tr.Marshal() if err != nil { t.Fatal(err) } rcvDigest = fmt.Sprintf("%x", sha1.Sum(rcvMsg)) if sndDigest != rcvDigest { fmt.Printf("sndMsg: %x\n", sndMsg) fmt.Printf("rcvMsg: %x\n", rcvMsg) t.Fatalf("inconsistent digest after sending and after receiving msg: %q != %q", sndDigest, rcvDigest) } if "52d9e295862bc3edad2841c412327a50d2c1b857" != rcvDigest { t.Fatalf("expected %q digest for structures, got %s", "52d9e295862bc3edad2841c412327a50d2c1b857", rcvDigest) } // Tests number if tr.sequence != 123 { t.Fatalf("expected %d, got %d", 123, tr.sequence) } // Tests strings for idx, str := range []string{"First alias", "Second alias", "Third alias"} { if tr.Aliases[idx] != str { t.Fatalf("expected %s, got %s", str, tr.Aliases[idx]) } } // Tests hash for key, val := range map[string]string{"endpoint": "tcp://localhost:5665"} { if tr.Headers[key] != val { t.Fatalf("expected %s, got %s", val, tr.Headers[key]) } } err = tr.Send(input) if err != nil { t.Fatal(err) } transit, err = Recv(output) if err != nil { t.Fatal(err) } if routingID != string(tr.RoutingID()) { t.Fatalf("expected %s, got %s", routingID, string(tr.RoutingID())) } }