// This is simple send function here i communicate with raft using simple request-response socket and ask to raft their status // like phase of raft and we can also close raft server using this function. // Here msg :- 1 means msg for ask phase of server and msg:- 0 means close the raft server func send(msg string, requester_C *zmq.Socket) string { // Decoding of phse receive by type 0 msg is 0 :- Follower, 1:- Candidate, 2:- Leader // By default phase :- "3" means no response from server and server is close requester_C.Send(msg, 0) phase := "3" if msg == "0" { return "0" } phase, _ = requester_C.Recv(0) type1 := s.Split(phase, " ")[0] value := s.Split(phase, " ")[1] if type1 == "-1" { if value == "0" { phase = "Follower" } else if value == "1" { phase = "Candidate" } else if value == "2" { phase = "Leader" } } else if type1 == "-2" { leaderId, _ = strconv.Atoi(value) } else if type1 == "0" { leaderId, _ = strconv.Atoi(s.Split(phase, " ")[2]) msg_index, _ := strconv.Atoi(value) send(message[msg_index], requester[leaderId-1]) return "0" } else { } return phase }
func snapshots(socket *zmq.Socket, srv *clonesrv_t) (err error) { msg, err := socket.RecvMessage(0) if err != nil { return } identity := msg[0] // Request is in second frame of message request := msg[1] if request != "ICANHAZ?" { err = errors.New("E: bad request, aborting") return } subtree := msg[2] // Send state socket to client for _, kvmsg := range srv.kvmap { if key, _ := kvmsg.GetKey(); strings.HasPrefix(key, subtree) { socket.Send(identity, zmq.SNDMORE) kvmsg.Send(socket) } } // Now send END message with sequence number log.Println("I: sending shapshot =", srv.sequence) socket.Send(identity, zmq.SNDMORE) kvmsg := kvmsg.NewKvmsg(srv.sequence) kvmsg.SetKey("KTHXBAI") kvmsg.SetBody(subtree) kvmsg.Send(socket) return }
func r(replier *zmq.Socket) { for { got, _ := replier.Recv(0) log.Println("Received", got) replier.Send(`{"jsonrpc":"2.0","id":"youpi","result":{"name":"test","hostname":"localtest","protocol":"test","port":0}}`, 0) } }
// SendReply will send the reply back to the connected reply proxy func SendReply(r *http.Response, body string, repsock *zmq.Socket) { rep := &messages.Reply{StatusCode: r.StatusCode, Body: body, Headers: r.Header} reps := rep.String() fmt.Printf("[PRIVATE] sending %d bytes or \n----\n%s\n-----\n", len(reps), reps) repsock.Send(reps, 0) fmt.Printf("[PRIVATE] sent %d bytes\n", len(reps)) }
// ZmqSendMulti Sends a slice of strings as a multi-part message func ZmqSendMulti(s *zmq.Socket, msg []string) { lastIdx := len(msg) - 1 for idx, part := range msg { if idx == lastIdx { s.Send(part, 0) } else { s.Send(part, zmq.SNDMORE) } } }
/****************************************************************************** * 概述: 订阅退订 * 函数名: dealCmd * 返回值: * 参数列表: 参数名 参数类型 取值范围 描述 * *******************************************************************************/ func (this *ZmqSocket) dealCmd(cmdSocket *zmq4.Socket) (int, error) { log4.Debug("start deal cmd...") for { //半包处理 cmdsStr, err0 := cmdSocket.Recv(zmq4.DONTWAIT) if err0 != nil { errno1 := zmq4.AsErrno(err0) switch errno1 { case zmq4.Errno(syscall.EAGAIN): return 0, nil case zmq4.Errno(syscall.EINTR): continue default: log4.Debug("zmq req Get err %v, %d!", errno1, errno1) } } if len(cmdsStr) == 0 { log4.Debug("deal cmd return") return 0, nil } ss := strings.Split(cmdsStr, " ") log4.Debug("recv cmd %s", cmdsStr) for i := 0; i < len(ss); i++ { if len(ss[i]) == 0 { continue } if ss[i] == "stop" { // log4.Debug("recv cmd will stop %s %s", this.mreqUrl, this.msubUrl) cmdSocket.Send("0", 0) return 1, nil } if !this.mChoose { // log4.Debug("recv cmd ,but notChoose so return") return 0, nil } if ss[i][0] == 'r' { if err := this.msubSocket.SetSubscribe(ss[i][1:]); err != nil { log4.Error("SetSubscribe(%s) falied, %s", ss[i][1:], err.Error()) return 0, err } log4.Debug("setSubscribe ok %s", ss[i][1:]) continue } if ss[i][0] == 'u' { if err := this.msubSocket.SetUnsubscribe(ss[i][1:]); err != nil { log4.Error("SetUnSubscribe(%s) falied, %s", ss[i][1:], err.Error()) return 0, err } log4.Debug("setUnSubscribe ok %s", ss[i][1:]) continue } } } return 0, nil }
func send(socket *zmq.Socket, update keyUpdate) error { var err error if _, err = socket.Send(update.key, zmq.SNDMORE); err != nil { return err } if _, err = socket.SendBytes(update.payload, 0); err != nil { return err } return nil }
func sendToClient(message string, header []string, title string, more zmq.Flag, frontend *zmq.Socket) { //fmt.Println("\t", title) for key := range header { //fmt.Printf("\tSending to client: %s\n", header[key]) frontend.Send(header[key], zmq.SNDMORE) } //fmt.Printf("\tSending to client: %s\n", message) frontend.Send(message, more) //fmt.Println("\tDone") }
// args: // - addr: multicast group/address to listen to // - port: port number; addr:port builds the mcast socket // - iface: name of network interface to listen to // - d_dl_sock: // - stopch: func ListenUDPMcast(addr, port, iface string, d_dl_sock *zmq.Socket, stopch chan bool) { eth, err := net.InterfaceByName(iface) if err != nil { fmt.Println("Error interface:", err.Error()) os.Exit(1) } group := net.ParseIP(addr) if group == nil { fmt.Println("Error: invalid group address:", addr) os.Exit(1) } // listen to all udp packets on mcast port c, err := net.ListenPacket("udp4", "0.0.0.0:"+port) if err != nil { fmt.Println("Error listening for mcast:", err.Error()) os.Exit(1) } // close the listener when the application closes defer c.Close() // join mcast group p := ipv4.NewPacketConn(c) if err := p.JoinGroup(eth, &net.UDPAddr{IP: group}); err != nil { fmt.Println("Error joining:", err.Error()) os.Exit(1) } fmt.Println("Listening on " + addr + ":" + port) // enable transmissons of control message if err := p.SetControlMessage(ipv4.FlagDst, true); err != nil { fmt.Println("Error control message", err.Error()) } c1 := devreader.MakeChannel(UMSocket{p, group}) LOOP: for { select { case v1 := <-c1: fmt.Println("received UDP multicast") // forward to coord node d_dl_sock.Send(string(v1), 0) case <-stopch: break LOOP } } }
func sendData(socket *zmq.Socket, key string, data interface{}, kind string) { bs, err := json.Marshal(data) if err != nil { abort(err, "could not marshal data") } encoded_data := string(bs) msg_key := fmt.Sprintf("%s-%s,%s", opts.App, opts.Env, key) if _, err := socket.Send(msg_key, zmq.DONTWAIT|zmq.SNDMORE); err != nil { abort(err, "could not send message part 1") } if _, err := socket.Send(encoded_data, zmq.DONTWAIT); err != nil { abort(err, "could not send message part 2") } if opts.Verbose { fmt.Printf("KEY: %s\n%s: %s\n", key, kind, encoded_data) } }
func solve(hand string, sock *zmq.Socket) []string { req := &scrabble.Request{Hand: hand} reqMsg, err := proto.Marshal(req) condlog.Fatal(err, "Unable to marshal message") _, err = sock.Send(string(reqMsg), 0) condlog.Fatal(err, "Unable to marshal message") resMsg, err := sock.Recv(0) condlog.Fatal(err, "Unable to receive response") res := &scrabble.Response{} err = proto.Unmarshal([]byte(resMsg), res) condlog.Fatal(err, "Unable to unmarshal request") return res.Words }
// This is simple send function here i communicate with raft using simple request-response socket and ask to raft their status // like phase of raft and we can also close raft server using this function. // Here msg :- 1 means msg for ask phase of server and msg:- 0 means close the raft server func send(msg int, requester *zmq.Socket) string { // Decoding of phse receive by type 0 msg is 0 :- Follower, 1:- Candidate, 2:- Leader // By default phase :- "3" means no response from server and server is close phase := "3" requester.Send(fmt.Sprintf("%d", msg), 0) if msg == 1 { phase, _ = requester.Recv(0) } if phase == "0" { phase = "Follower" } else if phase == "1" { phase = "Candidate" } else if phase == "2" { phase = "Leader" } return phase }
func serve(sock *zmq.Socket, solv *Solver) { for { requestMsg, err := sock.Recv(0) condlog.Fatal(err, "Unable to receive request") request := &scrabble.Request{} err = proto.Unmarshal([]byte(requestMsg), request) condlog.Fatal(err, "Unable to unmarshal request") result := solv.Solve(request.Hand) response := &scrabble.Response{Words: result} responseMsg, err := proto.Marshal(response) condlog.Fatal(err, "Unable to marshal response") _, err = sock.Send(string(responseMsg), 0) condlog.Fatal(err, "Unable to send response") } }
func SendToClient(signature, error_status, message string, frontend *zmq.Socket) { fmt.Printf("\tSending signature to client: %s\n", signature) frontend.Send(signature, zmq.SNDMORE) fmt.Printf("\tSending errorstatus to client: %s\n", error_status) frontend.Send(error_status, zmq.SNDMORE) fmt.Printf("\tSending message to client: %s\n", message) frontend.Send(message, 0) }
func TestConflate(t *testing.T) { var s_in, s_out *zmq.Socket defer func() { for _, s := range []*zmq.Socket{s_in, s_out} { if s != nil { s.SetLinger(0) s.Close() } } }() bind_to := "tcp://127.0.0.1:5555" err := zmq.SetIoThreads(1) if err != nil { t.Fatal("SetIoThreads(1):", err) } s_in, err = zmq.NewSocket(zmq.PULL) if err != nil { t.Fatal("NewSocket 1:", err) } err = s_in.SetConflate(true) if err != nil { t.Fatal("SetConflate(true):", err) } err = s_in.Bind(bind_to) if err != nil { t.Fatal("s_in.Bind:", err) } s_out, err = zmq.NewSocket(zmq.PUSH) if err != nil { t.Fatal("NewSocket 2:", err) } err = s_out.Connect(bind_to) if err != nil { t.Fatal("s_out.Connect:", err) } message_count := 20 for j := 0; j < message_count; j++ { _, err = s_out.Send(fmt.Sprint(j), 0) if err != nil { t.Fatalf("s_out.Send %d: %v", j, err) } } time.Sleep(time.Second) payload_recved, err := s_in.Recv(0) if err != nil { t.Error("s_in.Recv:", err) } else { i, err := strconv.Atoi(payload_recved) if err != nil { t.Error("strconv.Atoi:", err) } if i != message_count-1 { t.Error("payload_recved != message_count - 1") } } err = s_in.Close() s_in = nil if err != nil { t.Error("s_in.Close:", err) } err = s_out.Close() s_out = nil if err != nil { t.Error("s_out.Close:", err) } }
func bounce(server, client *zmq.Socket) (msg string, err error) { content := "12345678ABCDEFGH12345678abcdefgh" // Send message from client to server rc, err := client.Send(content, zmq.SNDMORE|zmq.DONTWAIT) if err != nil { return "client.Send SNDMORE|DONTWAIT:", err } if rc != 32 { return "client.Send SNDMORE|DONTWAIT:", err32 } rc, err = client.Send(content, zmq.DONTWAIT) if err != nil { return "client.Send DONTWAIT:", err } if rc != 32 { return "client.Send DONTWAIT:", err32 } // Receive message at server side msg, err = server.Recv(0) if err != nil { return "server.Recv 1:", err } // Check that message is still the same if msg != content { return "server.Recv 1:", errors.New(fmt.Sprintf("%q != %q", msg, content)) } rcvmore, err := server.GetRcvmore() if err != nil { return "server.GetRcvmore 1:", err } if !rcvmore { return "server.GetRcvmore 1:", errors.New(fmt.Sprint("rcvmore ==", rcvmore)) } // Receive message at server side msg, err = server.Recv(0) if err != nil { return "server.Recv 2:", err } // Check that message is still the same if msg != content { return "server.Recv 2:", errors.New(fmt.Sprintf("%q != %q", msg, content)) } rcvmore, err = server.GetRcvmore() if err != nil { return "server.GetRcvmore 2:", err } if rcvmore { return "server.GetRcvmore 2:", errors.New(fmt.Sprint("rcvmore == ", rcvmore)) } // The same, from server back to client // Send message from server to client rc, err = server.Send(content, zmq.SNDMORE) if err != nil { return "server.Send SNDMORE:", err } if rc != 32 { return "server.Send SNDMORE:", err32 } rc, err = server.Send(content, 0) if err != nil { return "server.Send 0:", err } if rc != 32 { return "server.Send 0:", err32 } // Receive message at client side msg, err = client.Recv(0) if err != nil { return "client.Recv 1:", err } // Check that message is still the same if msg != content { return "client.Recv 1:", errors.New(fmt.Sprintf("%q != %q", msg, content)) } rcvmore, err = client.GetRcvmore() if err != nil { return "client.GetRcvmore 1:", err } if !rcvmore { return "client.GetRcvmore 1:", errors.New(fmt.Sprint("rcvmore ==", rcvmore)) } // Receive message at client side msg, err = client.Recv(0) if err != nil { return "client.Recv 2:", err } // Check that message is still the same if msg != content { return "client.Recv 2:", errors.New(fmt.Sprintf("%q != %q", msg, content)) } rcvmore, err = client.GetRcvmore() if err != nil { return "client.GetRcvmore 2:", err } if rcvmore { return "client.GetRcvmore 2:", errors.New(fmt.Sprint("rcvmore == ", rcvmore)) } return "OK", nil }
func TestPoller(t *testing.T) { var sb, sc *zmq.Socket defer func() { for _, s := range []*zmq.Socket{sb, sc} { if s != nil { s.SetLinger(0) s.Close() } } }() sb, err := zmq.NewSocket(zmq.PAIR) if err != nil { t.Fatal("NewSocket:", err) } err = sb.Bind("tcp://127.0.0.1:9737") if err != nil { t.Fatal("sb.Bind:", err) } sc, err = zmq.NewSocket(zmq.PAIR) if err != nil { t.Fatal("NewSocket:", err) } err = sc.Connect("tcp://127.0.0.1:9737") if err != nil { t.Fatal("sc.Connect:", err) } poller := zmq.NewPoller() idxb := poller.Add(sb, 0) idxc := poller.Add(sc, 0) if idxb != 0 || idxc != 1 { t.Errorf("idxb=%d idxc=%d", idxb, idxc) } if pa, err := poller.PollAll(100 * time.Millisecond); err != nil { t.Error("PollAll 1:", err) } else if len(pa) != 2 { t.Errorf("PollAll 1 len = %d", len(pa)) } else if pa[0].Events != 0 || pa[1].Events != 0 { t.Errorf("PollAll 1 events = %v, %v", pa[0], pa[1]) } poller.Update(idxb, zmq.POLLOUT) poller.UpdateBySocket(sc, zmq.POLLIN) if pa, err := poller.PollAll(100 * time.Millisecond); err != nil { t.Error("PollAll 2:", err) } else if len(pa) != 2 { t.Errorf("PollAll 2 len = %d", len(pa)) } else if pa[0].Events != zmq.POLLOUT || pa[1].Events != 0 { t.Errorf("PollAll 2 events = %v, %v", pa[0], pa[1]) } poller.UpdateBySocket(sb, 0) content := "12345678ABCDEFGH12345678ABCDEFGH" // Send message from client to server if rc, err := sb.Send(content, zmq.DONTWAIT); err != nil { t.Error("sb.Send DONTWAIT:", err) } else if rc != 32 { t.Error("sb.Send DONTWAIT:", err32) } if pa, err := poller.PollAll(100 * time.Millisecond); err != nil { t.Error("PollAll 3:", err) } else if len(pa) != 2 { t.Errorf("PollAll 3 len = %d", len(pa)) } else if pa[0].Events != 0 || pa[1].Events != zmq.POLLIN { t.Errorf("PollAll 3 events = %v, %v", pa[0], pa[1]) } // Receive message if msg, err := sc.Recv(zmq.DONTWAIT); err != nil { t.Error("sb.Recv DONTWAIT:", err) } else if msg != content { t.Error("sb.Recv msg != content") } poller.UpdateBySocket(sb, zmq.POLLOUT) poller.Update(idxc, zmq.POLLIN) if pa, err := poller.PollAll(100 * time.Millisecond); err != nil { t.Error("PollAll 4:", err) } else if len(pa) != 2 { t.Errorf("PollAll 4 len = %d", len(pa)) } else if pa[0].Events != zmq.POLLOUT || pa[1].Events != 0 { t.Errorf("PollAll 4 events = %v, %v", pa[0], pa[1]) } err = sc.Close() sc = nil if err != nil { t.Error("sc.Close:", err) } err = sb.Close() sb = nil if err != nil { t.Error("sb.Close:", err) } }
// Send a request to a service func SendRequest(service Service, request, message string) (reply []string, err error) { // Bind to service if not already done var requester *zmq.Socket fmt.Println("Connecting to '", service.Name, "'' at '", service.Address, "'...") requester, err = zmq.NewSocket(zmq.REQ) if err != nil { log.Println(err) return } requester.Connect(service.Address) poller := zmq.NewPoller() poller.Add(requester, zmq.POLLIN) retries_left := REQUEST_RETRIES request_timeout := REQUEST_TIMEOUT if request == PPP_HEARTBEAT { retries_left = 1 request_timeout = 1500 * time.Millisecond } for retries_left > 0 { // Send message // The service required in first packet of envelope // The message for given service in second packet of envelope // Heartbeat messages only contain one message in envelope if request == PPP_HEARTBEAT { _, err = requester.Send(PPP_HEARTBEAT, 0) } else { _, err = requester.Send(request, zmq.SNDMORE) _, err = requester.Send(message, 0) } for expect_reply := true; expect_reply; { // Poll socket for a reply, with timeout var sockets []zmq.Polled sockets, err = poller.Poll(request_timeout) if err != nil { break // Interrupted } // Wait to receive reply if there are no more messages to send if len(sockets) > 0 { // Receive all replies in the envelope before processing var more bool for count := 0; ; count++ { var rep string rep, err = requester.Recv(0) if err != nil { retries_left-- break } reply = append(reply, rep) // Unpacking three parts from the message envelope // The first part: the expected service reply signature // The second part is either: // a. error state (empty if no error) OR // b. the heartbeat reply of the server // The third part: the actual message if count == 0 && rep != service.Reply { err = errors.New("ServiceListOutdated:Bound to wrong service") retries_left = 0 break } if count == 1 && rep != "" && rep != PPP_READY { err = errors.New(rep) retries_left = 0 break } // Break from loop if there are no more messages or // an error condition occurs more, err = requester.GetRcvmore() if !more || err != nil { retries_left-- break } } // If there was an error retrieving the message, then we // should still expect replies if err != nil { break } // All messages retrieved from packet successfully // Leave the retrieve/retry loops retries_left = 0 expect_reply = false } else { retries_left-- if retries_left == 0 { if err == nil { err = errors.New("Error:TimeOut") } requester.Close() return } else { err = nil reply = nil fmt.Println("No response from server, retrying...") // Old socket is confused; close it and open a new one requester.Close() requester, _ = zmq.NewSocket(zmq.REQ) requester.Connect(service.Address) // Recreate poller for new client poller = zmq.NewPoller() poller.Add(requester, zmq.POLLIN) // Send request again, on the new socket if request == PPP_HEARTBEAT { _, err = requester.Send(PPP_HEARTBEAT, 0) } else { _, err = requester.Send(request, zmq.SNDMORE) _, err = requester.Send(message, 0) } } } } } fmt.Println("\tReceived: ", reply) // Deall with invalid/distorted replies first // Followed by heartbeat replies // Then package reply for return to the function caller if len(reply) < 2 { err = errors.New(fmt.Sprintf("Error:UnexpectedReply:%s", err)) requester.Close() return } if reply[1] == PPP_READY { reply = append(reply, reply[1]) } reply = reply[2:] requester.Close() return }
func bounce(server, client *zmq.Socket, willfail bool) { content := "12345678ABCDEFGH12345678abcdefgh" // Send message from client to server rc, err := client.Send(content, zmq.SNDMORE|zmq.DONTWAIT) if checkErr0(err, 1) { return } if rc != 32 { checkErr0(errors.New("rc != 32"), 2) } rc, err = client.Send(content, zmq.DONTWAIT) if checkErr0(err, 3) { return } if rc != 32 { checkErr0(errors.New("rc != 32"), 4) } // Receive message at server side msg, err := server.Recv(0) if checkErr0(e(err, willfail), 5) { return } // Check that message is still the same if msg != content { checkErr0(errors.New(fmt.Sprintf("%q != %q", msg, content)), 6) } rcvmore, err := server.GetRcvmore() if checkErr0(err, 7) { return } if !rcvmore { checkErr0(errors.New(fmt.Sprint("rcvmore ==", rcvmore)), 8) return } // Receive message at server side msg, err = server.Recv(0) if checkErr0(err, 9) { return } // Check that message is still the same if msg != content { checkErr0(errors.New(fmt.Sprintf("%q != %q", msg, content)), 10) } rcvmore, err = server.GetRcvmore() if checkErr0(err, 11) { return } if rcvmore { checkErr0(errors.New(fmt.Sprint("rcvmore == ", rcvmore)), 12) return } // The same, from server back to client // Send message from server to client rc, err = server.Send(content, zmq.SNDMORE) if checkErr0(err, 13) { return } if rc != 32 { checkErr0(errors.New("rc != 32"), 14) } rc, err = server.Send(content, 0) if checkErr0(err, 15) { return } if rc != 32 { checkErr0(errors.New("rc != 32"), 16) } // Receive message at client side msg, err = client.Recv(0) if checkErr0(err, 17) { return } // Check that message is still the same if msg != content { checkErr0(errors.New(fmt.Sprintf("%q != %q", msg, content)), 18) } rcvmore, err = client.GetRcvmore() if checkErr0(err, 19) { return } if !rcvmore { checkErr0(errors.New(fmt.Sprint("rcvmore ==", rcvmore)), 20) return } // Receive message at client side msg, err = client.Recv(0) if checkErr0(err, 21) { return } // Check that message is still the same if msg != content { checkErr0(errors.New(fmt.Sprintf("%q != %q", msg, content)), 22) } rcvmore, err = client.GetRcvmore() if checkErr0(err, 23) { return } if rcvmore { checkErr0(errors.New(fmt.Sprint("rcvmore == ", rcvmore)), 24) return } }
func TestDisconnectInproc(t *testing.T) { var pubSocket, subSocket *zmq.Socket defer func() { for _, s := range []*zmq.Socket{pubSocket, subSocket} { if s != nil { s.SetLinger(0) s.Close() } } }() publicationsReceived := 0 isSubscribed := false pubSocket, err := zmq.NewSocket(zmq.XPUB) if err != nil { t.Fatal("NewSocket XPUB:", err) } subSocket, err = zmq.NewSocket(zmq.SUB) if err != nil { t.Fatal("NewSocket SUB:", err) } err = subSocket.SetSubscribe("foo") if err != nil { t.Fatal("subSocket.SetSubscribe:", err) } err = pubSocket.Bind("inproc://someInProcDescriptor") if err != nil { t.Fatal("pubSocket.Bind:", err) } iteration := 0 poller := zmq.NewPoller() poller.Add(subSocket, zmq.POLLIN) // read publications poller.Add(pubSocket, zmq.POLLIN) // read subscriptions for { sockets, err := poller.Poll(100 * time.Millisecond) if err != nil { t.Error("Poll:", err) break // Interrupted } for _, socket := range sockets { if socket.Socket == pubSocket { for { buffer, err := pubSocket.Recv(0) if err != nil { t.Fatal("pubSocket.Recv", err) } exp := "\x01foo" if isSubscribed { exp = "\x00foo" } if buffer != exp { t.Errorf("pubSocket.Recv: expected %q, got %q", exp, buffer) } if buffer[0] == 0 { if isSubscribed != true { t.Errorf("Poller: expected subscribed") } isSubscribed = false } else { if isSubscribed != false { t.Errorf("Poller: expected not subscribed") } isSubscribed = true } more, err := pubSocket.GetRcvmore() if err != nil { t.Fatal("pubSocket.GetRcvmore:", err) } if !more { break // Last message part } } break } } for _, socket := range sockets { if socket.Socket == subSocket { for _, exp := range []string{"foo", "this is foo!", "", ""} { msg, err := subSocket.Recv(0) if err != nil { t.Fatal("subSocket.Recv:", err) } if msg != exp { t.Errorf("subSocket.Recv: expected %q, got %q", exp, msg) } more, err := subSocket.GetRcvmore() if err != nil { t.Fatal("subSocket.GetRcvmore:", err) } if !more { publicationsReceived++ break // Last message part } } break } } if iteration == 1 { err := subSocket.Connect("inproc://someInProcDescriptor") if err != nil { t.Fatal("subSocket.Connect", err) } } if iteration == 4 { err := subSocket.Disconnect("inproc://someInProcDescriptor") if err != nil { t.Fatal("subSocket.Disconnect", err) } } if iteration > 4 && len(sockets) == 0 { break } _, err = pubSocket.Send("foo", zmq.SNDMORE) if err != nil { t.Fatal("pubSocket.Send 1", err) } _, err = pubSocket.Send("this is foo!", 0) if err != nil { t.Fatal("pubSocket.Send 2", err) } iteration++ } if publicationsReceived != 3 { t.Error("publicationsReceived != 3 ") } if isSubscribed { t.Error("isSubscribed") } err = pubSocket.Close() pubSocket = nil if err != nil { t.Error("pubSocket.Close:", err) } err = subSocket.Close() subSocket = nil if err != nil { t.Error("subSocket.Close:", err) } }
func Example_test_hwm() { MAX_SENDS := 10000 BIND_FIRST := 1 CONNECT_FIRST := 2 test_defaults := func() int { // Set up bind socket bind_socket, err := zmq.NewSocket(zmq.PULL) if checkErr(err) { return 0 } defer func() { err := bind_socket.Close() checkErr(err) }() err = bind_socket.Bind("inproc://a") if checkErr(err) { return 0 } // Set up connect socket connect_socket, err := zmq.NewSocket(zmq.PUSH) if checkErr(err) { return 0 } defer func() { err := connect_socket.Close() checkErr(err) }() err = connect_socket.Connect("inproc://a") if checkErr(err) { return 0 } // Send until we block send_count := 0 for send_count < MAX_SENDS { _, err := connect_socket.Send("", zmq.DONTWAIT) if err != nil { break } send_count++ } // Now receive all sent messages recv_count := 0 for { _, err := bind_socket.Recv(zmq.DONTWAIT) if err != nil { break } recv_count++ } fmt.Println("send_count == recv_count:", send_count == recv_count) return send_count } count_msg := func(send_hwm, recv_hwm, testType int) int { var bind_socket, connect_socket *zmq.Socket var err error if testType == BIND_FIRST { // Set up bind socket bind_socket, err = zmq.NewSocket(zmq.PULL) if checkErr(err) { return 0 } defer func() { err := bind_socket.Close() checkErr(err) }() err = bind_socket.SetRcvhwm(recv_hwm) if checkErr(err) { return 0 } err = bind_socket.Bind("inproc://a") if checkErr(err) { return 0 } // Set up connect socket connect_socket, err = zmq.NewSocket(zmq.PUSH) if checkErr(err) { return 0 } defer func() { err := connect_socket.Close() checkErr(err) }() err = connect_socket.SetSndhwm(send_hwm) if checkErr(err) { return 0 } err = connect_socket.Connect("inproc://a") if checkErr(err) { return 0 } } else { // Set up connect socket connect_socket, err = zmq.NewSocket(zmq.PUSH) if checkErr(err) { return 0 } defer func() { err := connect_socket.Close() checkErr(err) }() err = connect_socket.SetSndhwm(send_hwm) if checkErr(err) { return 0 } err = connect_socket.Connect("inproc://a") if checkErr(err) { return 0 } // Set up bind socket bind_socket, err = zmq.NewSocket(zmq.PULL) if checkErr(err) { return 0 } defer func() { err := bind_socket.Close() checkErr(err) }() err = bind_socket.SetRcvhwm(recv_hwm) if checkErr(err) { return 0 } err = bind_socket.Bind("inproc://a") if checkErr(err) { return 0 } } // Send until we block send_count := 0 for send_count < MAX_SENDS { _, err := connect_socket.Send("", zmq.DONTWAIT) if err != nil { break } send_count++ } // Now receive all sent messages recv_count := 0 for { _, err := bind_socket.Recv(zmq.DONTWAIT) if err != nil { break } recv_count++ } fmt.Println("send_count == recv_count:", send_count == recv_count) // Now it should be possible to send one more. _, err = connect_socket.Send("", 0) if checkErr(err) { return 0 } // Consume the remaining message. _, err = bind_socket.Recv(0) checkErr(err) return send_count } test_inproc_bind_first := func(send_hwm, recv_hwm int) int { return count_msg(send_hwm, recv_hwm, BIND_FIRST) } test_inproc_connect_first := func(send_hwm, recv_hwm int) int { return count_msg(send_hwm, recv_hwm, CONNECT_FIRST) } test_inproc_connect_and_close_first := func(send_hwm, recv_hwm int) int { // Set up connect socket connect_socket, err := zmq.NewSocket(zmq.PUSH) if checkErr(err) { return 0 } err = connect_socket.SetSndhwm(send_hwm) if checkErr(err) { connect_socket.Close() return 0 } err = connect_socket.Connect("inproc://a") if checkErr(err) { connect_socket.Close() return 0 } // Send until we block send_count := 0 for send_count < MAX_SENDS { _, err := connect_socket.Send("", zmq.DONTWAIT) if err != nil { break } send_count++ } // Close connect err = connect_socket.Close() if checkErr(err) { return 0 } // Set up bind socket bind_socket, err := zmq.NewSocket(zmq.PULL) if checkErr(err) { return 0 } defer func() { err := bind_socket.Close() checkErr(err) }() err = bind_socket.SetRcvhwm(recv_hwm) if checkErr(err) { return 0 } err = bind_socket.Bind("inproc://a") if checkErr(err) { return 0 } // Now receive all sent messages recv_count := 0 for { _, err := bind_socket.Recv(zmq.DONTWAIT) if err != nil { break } recv_count++ } fmt.Println("send_count == recv_count:", send_count == recv_count) return send_count } // Default values are 1000 on send and 1000 one receive, so 2000 total fmt.Println("Default values") count := test_defaults() fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) // Infinite send and receive buffer fmt.Println("\nInfinite send and receive") count = test_inproc_bind_first(0, 0) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) count = test_inproc_connect_first(0, 0) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) // Infinite send buffer fmt.Println("\nInfinite send buffer") count = test_inproc_bind_first(1, 0) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) count = test_inproc_connect_first(1, 0) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) // Infinite receive buffer fmt.Println("\nInfinite receive buffer") count = test_inproc_bind_first(0, 1) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) count = test_inproc_connect_first(0, 1) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) // Send and recv buffers hwm 1, so total that can be queued is 2 fmt.Println("\nSend and recv buffers hwm 1") count = test_inproc_bind_first(1, 1) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) count = test_inproc_connect_first(1, 1) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) // Send hwm of 1, send before bind so total that can be queued is 1 fmt.Println("\nSend hwm of 1, send before bind") count = test_inproc_connect_and_close_first(1, 0) fmt.Println("count:", count) time.Sleep(100 * time.Millisecond) fmt.Println("\nDone") // Output: // Default values // send_count == recv_count: true // count: 2000 // // Infinite send and receive // send_count == recv_count: true // count: 10000 // send_count == recv_count: true // count: 10000 // // Infinite send buffer // send_count == recv_count: true // count: 10000 // send_count == recv_count: true // count: 10000 // // Infinite receive buffer // send_count == recv_count: true // count: 10000 // send_count == recv_count: true // count: 10000 // // Send and recv buffers hwm 1 // send_count == recv_count: true // count: 2 // send_count == recv_count: true // count: 2 // // Send hwm of 1, send before bind // send_count == recv_count: true // count: 1 // // Done }
func TestHwm(t *testing.T) { MAX_SENDS := 10000 BIND_FIRST := 1 CONNECT_FIRST := 2 test_defaults := func() (result int) { result = -1 // Set up bind socket bind_socket, err := zmq.NewSocket(zmq.PULL) if err != nil { t.Error("NewSocket:", err) return } defer func() { err := bind_socket.Close() if err != nil { t.Error("bind_socket.Close:", err) } }() err = bind_socket.Bind("inproc://a") if err != nil { t.Error("bind_socket.Bind:", err) return } // Set up connect socket connect_socket, err := zmq.NewSocket(zmq.PUSH) if err != nil { t.Error("NewSocket:", err) return } defer func() { err := connect_socket.Close() if err != nil { t.Error("connect_socket.Close:", err) } }() err = connect_socket.Connect("inproc://a") if err != nil { t.Error("connect_socket.Connect:", err) return } // Send until we block send_count := 0 for send_count < MAX_SENDS { _, err := connect_socket.Send("", zmq.DONTWAIT) if err != nil { break } send_count++ } // Now receive all sent messages recv_count := 0 for { _, err := bind_socket.Recv(zmq.DONTWAIT) if err != nil { break } recv_count++ } if send_count != recv_count { t.Error("test_defaults: send_count == recv_count") } return send_count } count_msg := func(send_hwm, recv_hwm, testType int) (result int) { result = -1 var bind_socket, connect_socket *zmq.Socket var err error if testType == BIND_FIRST { // Set up bind socket bind_socket, err = zmq.NewSocket(zmq.PULL) if err != nil { t.Error("NewSocket:", err) return } defer func() { err := bind_socket.Close() if err != nil { t.Error("bind_socket.Close:", err) } }() err = bind_socket.SetRcvhwm(recv_hwm) if err != nil { t.Error("bind_socket.SetRcvhwm:", err) return } err = bind_socket.Bind("inproc://a") if err != nil { t.Error("bind_socket.Bind:", err) return } // Set up connect socket connect_socket, err = zmq.NewSocket(zmq.PUSH) if err != nil { t.Error("NewSocket:", err) return } defer func() { err := connect_socket.Close() if err != nil { t.Error(err) } }() err = connect_socket.SetSndhwm(send_hwm) if err != nil { t.Error("connect_socket.SetSndhwm:", err) return } err = connect_socket.Connect("inproc://a") if err != nil { t.Error("connect_socket.Connect:", err) return } } else { // Set up connect socket connect_socket, err = zmq.NewSocket(zmq.PUSH) if err != nil { t.Error("NewSocket:", err) return } defer func() { err := connect_socket.Close() if err != nil { t.Error("connect_socket.Close:", err) } }() err = connect_socket.SetSndhwm(send_hwm) if err != nil { t.Error("connect_socket.SetSndhwm:", err) return } err = connect_socket.Connect("inproc://a") if err != nil { t.Error("connect_socket.Connect:", err) return } // Set up bind socket bind_socket, err = zmq.NewSocket(zmq.PULL) if err != nil { t.Error("NewSocket:", err) return } defer func() { err := bind_socket.Close() if err != nil { t.Error("bind_socket.Close:", err) } }() err = bind_socket.SetRcvhwm(recv_hwm) if err != nil { t.Error("bind_socket.SetRcvhwm:", err) return } err = bind_socket.Bind("inproc://a") if err != nil { t.Error("bind_socket.Bind:", err) return } } // Send until we block send_count := 0 for send_count < MAX_SENDS { _, err := connect_socket.Send("", zmq.DONTWAIT) if err != nil { break } send_count++ } // Now receive all sent messages recv_count := 0 for { _, err := bind_socket.Recv(zmq.DONTWAIT) if err != nil { break } recv_count++ } if send_count != recv_count { t.Error("count_msg: send_count != recv_count") } // Now it should be possible to send one more. _, err = connect_socket.Send("", 0) if err != nil { t.Error("connect_socket.Send:", err) return } // Consume the remaining message. _, err = bind_socket.Recv(0) if err != nil { t.Error("bind_socket.Recv:", err) } return send_count } test_inproc_bind_first := func(send_hwm, recv_hwm int) int { return count_msg(send_hwm, recv_hwm, BIND_FIRST) } test_inproc_connect_first := func(send_hwm, recv_hwm int) int { return count_msg(send_hwm, recv_hwm, CONNECT_FIRST) } test_inproc_connect_and_close_first := func(send_hwm, recv_hwm int) (result int) { result = -1 // Set up connect socket connect_socket, err := zmq.NewSocket(zmq.PUSH) if err != nil { t.Error("NewSocket:", err) return } defer func() { if connect_socket != nil { connect_socket.Close() } }() err = connect_socket.SetSndhwm(send_hwm) if err != nil { t.Error("connect_socket.SetSndhwm:", err) return } err = connect_socket.Connect("inproc://a") if err != nil { t.Error("connect_socket.Connect:", err) return } // Send until we block send_count := 0 for send_count < MAX_SENDS { _, err := connect_socket.Send("", zmq.DONTWAIT) if err != nil { break } send_count++ } // Close connect err = connect_socket.Close() connect_socket = nil if err != nil { t.Error("connect_socket.Close:", err) return } // Set up bind socket bind_socket, err := zmq.NewSocket(zmq.PULL) if err != nil { t.Error("NewSocket:", err) return } defer func() { err := bind_socket.Close() if err != nil { t.Error("bind_socket.Close:", err) } }() err = bind_socket.SetRcvhwm(recv_hwm) if err != nil { t.Error("bind_socket.SetRcvhwm:", err) return } err = bind_socket.Bind("inproc://a") if err != nil { t.Error("bind_socket.Bind:", err) return } // Now receive all sent messages recv_count := 0 for { _, err := bind_socket.Recv(zmq.DONTWAIT) if err != nil { break } recv_count++ } if send_count != recv_count { t.Error("test_inproc_connect_and_close_first: send_count != recv_count") } return send_count } // Default values are 1000 on send and 1000 one receive, so 2000 total if count := test_defaults(); count != 2000 { t.Errorf("test_defaults: expected 2000, got %d", count) } time.Sleep(100 * time.Millisecond) // Infinite send and receive buffer if count := test_inproc_bind_first(0, 0); count != MAX_SENDS { t.Errorf("test_inproc_bind_first(0, 0): expected %d, got %d", MAX_SENDS, count) } time.Sleep(100 * time.Millisecond) if count := test_inproc_connect_first(0, 0); count != MAX_SENDS { t.Errorf("test_inproc_connect_first(0, 0): expected %d, got %d", MAX_SENDS, count) } time.Sleep(100 * time.Millisecond) // Infinite send buffer if count := test_inproc_bind_first(1, 0); count != MAX_SENDS { t.Errorf("test_inproc_bind_first(1, 0): expected %d, got %d", MAX_SENDS, count) } time.Sleep(100 * time.Millisecond) if count := test_inproc_connect_first(1, 0); count != MAX_SENDS { t.Errorf("test_inproc_connect_first(1, 0): expected %d, got %d", MAX_SENDS, count) } time.Sleep(100 * time.Millisecond) // Infinite receive buffer if count := test_inproc_bind_first(0, 1); count != MAX_SENDS { t.Errorf("test_inproc_bind_first(0, 1): expected %d, got %d", MAX_SENDS, count) } time.Sleep(100 * time.Millisecond) if count := test_inproc_connect_first(0, 1); count != MAX_SENDS { t.Errorf("test_inproc_connect_first(0, 1): expected %d, got %d", MAX_SENDS, count) } time.Sleep(100 * time.Millisecond) // Send and recv buffers hwm 1, so total that can be queued is 2 if count := test_inproc_bind_first(1, 1); count != 2 { t.Errorf("test_inproc_bind_first(1, 1): expected 2, got %d", count) } time.Sleep(100 * time.Millisecond) if count := test_inproc_connect_first(1, 1); count != 2 { t.Errorf("test_inproc_connect_first(1, 1): expected 2, got %d", count) } time.Sleep(100 * time.Millisecond) // Send hwm of 1, send before bind so total that can be queued is 1 if count := test_inproc_connect_and_close_first(1, 0); count != 1 { t.Errorf("test_inproc_connect_and_close_first(1, 0): expected 1, got %d", count) } time.Sleep(100 * time.Millisecond) }
// args: // - host: hostname // - tcp_port: port number; host:port builds the tcp socket // - iface: name of network interface to listen to // - c_sock: // - d_dl_sock: // - d_ul_sock: func ListenTCP(host, tcp_port, iface string, c_sock, d_dl_sock, d_ul_sock *zmq.Socket) { // WDC state connected := 0 // control channel to stop listening to coordnode cn_stopch := make(chan bool) // control channel to stop listening udp mcast mcast_stopch := make(chan bool) // Listen for TCP incoming connections t, err := net.Listen("tcp", host+":"+tcp_port) if err != nil { fmt.Println("Error listening:", err.Error()) os.Exit(1) } // Close the listener when the application closes defer t.Close() // Make a buffer to hold incoming data buf := make([]byte, 1024) for { // Listen for an incoming TCP connection fmt.Println("Listening on " + host + ":" + tcp_port) // this blocks until someone attempts to connect t_conn, err := t.Accept() if err != nil { fmt.Println("Error accepting:", err.Error()) continue } defer t_conn.Close() for { // Read the incoming data from accepted conn into the buffer // this blocks until some data are actually received dlen, err := t_conn.Read(buf) if err != nil { if err.Error() == "EOF" { if connected == 1 { // stop listening to CoordNode cn_stopch <- true // stop listening UDP mcast mcast_stopch <- true connected = 0 } break } else { fmt.Println("Error reading:", err.Error()) continue } } if len(buf) == 0 || (int(buf[0])+1) != dlen { fmt.Println("Error: Inconsistent message length") continue } fmt.Println("received TCP command", hex.EncodeToString(buf[:dlen])) switch buf[1] { case 0x01: // WDC_CONNECTION_REQ fmt.Println("received connection request:", hex.EncodeToString(buf[:dlen])) // TODO: check expected len of WDC_CONNECTION_REQ if dlen < 10 { // <-- this is currently arbitrary fmt.Println("Error: wrong WDC_CONNECTION_REQ len") continue } if connected == 1 { msg.WDC_ERROR[2] = byte(msg.BUSY_CONNECTED) t_conn.Write(msg.WDC_ERROR) continue } msg.WDC_GET_STATUS_RES[0] = byte(dlen) copy(msg.WDC_GET_STATUS_RES[3:], buf[2:]) // orig msg is very long with trailing zeroes // truncate to dlen msg.WDC_GET_STATUS_RES = msg.WDC_GET_STATUS_RES[:dlen+1] // send message to CoordNode and get a return c_sock.Send(string(buf[:dlen]), 0) cn_buf, _ := c_sock.Recv(0) if int(cn_buf[0])+1 != len(cn_buf) || cn_buf[1] != 0x02 { // WDC_CONNECTION_RES fmt.Println("Error on reading from CoordNode") msg.WDC_ERROR[2] = byte(msg.SERIAL_PORT) t_conn.Write(msg.WDC_ERROR) continue } // get multicast info var MCAST_PORT uint16 binary.Read(bytes.NewReader(buf[8:10]), binary.LittleEndian, &MCAST_PORT) MCAST_ADDR := buf[10 : dlen-1] // create UDP socket to server SERVER_SOCK := t_conn.RemoteAddr().String() SERVER_IP := strings.Split(SERVER_SOCK, ":")[0] var SERVER_UDP_PORT uint16 binary.Read(bytes.NewReader(buf[6:8]), binary.LittleEndian, &SERVER_UDP_PORT) // create UDP address from string udpaddr, err := net.ResolveUDPAddr("udp", SERVER_IP+":"+fmt.Sprintf("%d", SERVER_UDP_PORT)) if err != nil { fmt.Println("Error resolving UDP:", err.Error()) continue } // dial UDP u_conn, err := net.DialUDP("udp", nil, udpaddr) if err != nil { fmt.Println("Error server UDP:", err.Error()) msg.WDC_ERROR[2] = byte(msg.CONNECTING) t_conn.Write(msg.WDC_ERROR) continue } fmt.Printf("Server UDP is at: %s:%d\n", SERVER_IP, SERVER_UDP_PORT) // close UDP when the application closes defer u_conn.Close() // set and send connection response copy(msg.WDC_CONNECTION_RES, cn_buf) // reply to server t_conn.Write(msg.WDC_CONNECTION_RES) fmt.Println("sent connection response:", hex.EncodeToString(msg.WDC_CONNECTION_RES)) // Serve UDP mcast in a new goroutine go ListenUDPMcast(string(MCAST_ADDR), fmt.Sprintf("%d", MCAST_PORT), iface, d_dl_sock, mcast_stopch) // Start listening to CoordNode go ListenCoordNode(d_ul_sock, u_conn, cn_stopch) connected = 1 case 0x03: // WDC_DISCONNECTION_REQ fmt.Println("received disconnection request") if connected == 1 { // send disconnect to CoordNode (bye) c_sock.Send(string(buf[:dlen]), 0) req_ack, _ := c_sock.Recv(0) msg.WDC_DISCONNECTION_REQ_ACK = []byte(req_ack) // stop listening to CoordNode cn_stopch <- true // stop listening UDP mcast mcast_stopch <- true // TODO u_conn.Close() (u_conn undefined) // send disconnect ack to server t_conn.Write(msg.WDC_DISCONNECTION_REQ_ACK) fmt.Println("sent disconnection request ack, bye!") } connected = 0 case 0x05: // WDC_GET_STATUS_REQ fmt.Println("received WDC status request") msg.WDC_GET_STATUS_RES[2] = byte(connected) t_conn.Write(msg.WDC_GET_STATUS_RES) fmt.Println("sent WDC status response:", hex.EncodeToString(msg.WDC_GET_STATUS_RES)) case 0x07, 0x09: // WDC_SET_COOR_LONG_ADDR_REQ || // WDC_RESET_REQ if connected == 1 { msg.WDC_ERROR[2] = byte(msg.BUSY_CONNECTED) t_conn.Write(msg.WDC_ERROR) } else { fmt.Println("received long address set req") c_sock.Send(string(buf[:dlen]), 0) cn_buf, _ := c_sock.Recv(0) if int(cn_buf[0])+1 != len(cn_buf) { fmt.Println("Error reading from CoordNode") continue } copy(msg.WDC_SET_COOR_LONG_ADDR_REQ_ACK, cn_buf) t_conn.Write(msg.WDC_SET_COOR_LONG_ADDR_REQ_ACK) fmt.Println("sent long address set ack") if buf[1] == 0x09 { fmt.Println("received reset request") t_conn.Write(msg.WDC_RESET_REQ_ACK) fmt.Println("sent reset ack, bye!") // Exit will close UDP, TCP, UDP mcast // TODO: serial; reboot instead of app exit os.Exit(0) } } case 0x0B: // WDC_REPLACE_SECURITY_POLICY fmt.Println("received replace security policy") if connected == 0 { msg.WDC_ERROR[2] = byte(msg.BUSY_CONNECTED) // TODO: not correct semantically t_conn.Write(msg.WDC_ERROR) continue } fmt.Println("replace security policy command:", hex.EncodeToString(buf[:dlen])) msg.WDC_REPLACE_SECURITY_POLICY_ACK[2] = 0x00 t_conn.Write(msg.WDC_REPLACE_SECURITY_POLICY_ACK) fmt.Println("sent replace security policy ack") case 0x0D: // WDC_REPLACE_SESSION_KEYS fmt.Println("received replace session keys") if connected == 0 { msg.WDC_ERROR[2] = byte(msg.BUSY_CONNECTED) // TODO: not correct semantically t_conn.Write(msg.WDC_ERROR) continue } fmt.Println("replace session keys command:", hex.EncodeToString(buf[:dlen])) msg.WDC_REPLACE_SESSIONKEYS_ACK[2] = 0x00 t_conn.Write(msg.WDC_REPLACE_SESSIONKEYS_ACK) fmt.Println("sent replace session keys ack") default: fmt.Println("received unknown command") msg.WDC_ERROR[2] = byte(msg.WRONG_CMD) t_conn.Write(msg.WDC_ERROR) } } // TODO cleanup on exiting loop } }
func TestRemoteEndpoint(t *testing.T) { if _, minor, _ := zmq.Version(); minor < 1 { t.Skip("RemoteEndpoint not avalable in ZeroMQ versions prior to 4.1.0") } addr := "tcp://127.0.0.1:9560" peer := "127.0.0.1" var rep, req *zmq.Socket defer func() { for _, s := range []*zmq.Socket{rep, req} { if s != nil { s.SetLinger(0) s.Close() } } }() rep, err := zmq.NewSocket(zmq.REP) if err != nil { t.Fatal("NewSocket:", err) } req, err = zmq.NewSocket(zmq.REQ) if err != nil { t.Fatal("NewSocket:", err) } if err = rep.Bind(addr); err != nil { t.Fatal("rep.Bind:", err) } if err = req.Connect(addr); err != nil { t.Fatal("req.Connect:", err) } tmp := "test" if _, err = req.Send(tmp, 0); err != nil { t.Fatal("req.Send:", err) } // get message with peer address (remote endpoint) msg, props, err := rep.RecvWithMetadata(0, "Peer-Address") if err != nil { t.Fatal("rep.RecvWithMetadata:", err) return } if msg != tmp { t.Errorf("rep.RecvWithMetadata: expected %q, got %q", tmp, msg) } if p := props["Peer-Address"]; p != peer { t.Errorf("rep.RecvWithMetadata: expected Peer-Address == %q, got %q", peer, p) } err = rep.Close() rep = nil if err != nil { t.Fatal("rep.Close:", err) } err = req.Close() req = nil if err != nil { t.Fatal("req.Close:", err) } }
func bounce(server, client *zmq.Socket) { content := "12345678ABCDEFGH12345678abcdefgh" // Send message from client to server rc, err := client.Send(content, zmq.SNDMORE|zmq.DONTWAIT) if checkErr0(err) { return } if rc != 32 { checkErr0(errors.New("rc != 32")) } rc, err = client.Send(content, zmq.DONTWAIT) if checkErr0(err) { return } if rc != 32 { checkErr0(errors.New("rc != 32")) } // Receive message at server side msg, err := server.Recv(0) if checkErr0(err) { return } // Check that message is still the same if msg != content { checkErr0(errors.New(fmt.Sprintf("%q != %q", msg, content))) } rcvmore, err := server.GetRcvmore() if checkErr0(err) { return } if !rcvmore { checkErr0(errors.New(fmt.Sprint("rcvmore ==", rcvmore))) return } // Receive message at server side msg, err = server.Recv(0) if checkErr0(err) { return } // Check that message is still the same if msg != content { checkErr0(errors.New(fmt.Sprintf("%q != %q", msg, content))) } rcvmore, err = server.GetRcvmore() if checkErr0(err) { return } if rcvmore { checkErr0(errors.New(fmt.Sprint("rcvmore == ", rcvmore))) return } // The same, from server back to client // Send message from server to client rc, err = server.Send(content, zmq.SNDMORE) if checkErr0(err) { return } if rc != 32 { checkErr0(errors.New("rc != 32")) } rc, err = server.Send(content, 0) if checkErr0(err) { return } if rc != 32 { checkErr0(errors.New("rc != 32")) } // Receive message at client side msg, err = client.Recv(0) if checkErr0(err) { return } // Check that message is still the same if msg != content { checkErr0(errors.New(fmt.Sprintf("%q != %q", msg, content))) } rcvmore, err = client.GetRcvmore() if checkErr0(err) { return } if !rcvmore { checkErr0(errors.New(fmt.Sprint("rcvmore ==", rcvmore))) return } // Receive message at client side msg, err = client.Recv(0) if checkErr0(err) { return } // Check that message is still the same if msg != content { checkErr0(errors.New(fmt.Sprintf("%q != %q", msg, content))) } rcvmore, err = client.GetRcvmore() if checkErr0(err) { return } if rcvmore { checkErr0(errors.New(fmt.Sprint("rcvmore == ", rcvmore))) return } }