Пример #1
0
/****************************************************************
	Receiving Message from all Servers
****************************************************************/
func receiveMessage(recSockets *zmq.Socket, conn *Connection) {

	for {
		select {
		// Stopping Go Routine
		case _, _ = <-conn.stopGoRoutine:

			return

		default:
			recSockets.SetRcvtimeo(500 * time.Millisecond)
			msg, err := recSockets.Recv(0)

			if err == nil {
				msg_array := strings.Split(msg, ":")

				msg_seq := msg_array[0]
				isLeader := msg_array[1]
				leaderId, _ := strconv.Atoi(msg_array[2])

				count, _ := strconv.Atoi(isLeader)

				// Added the LeaderCount if the response belongs to corresponding request
				if strconv.Itoa(conn.attempt) == msg_seq {
					conn.recvCount += 1
					conn.leaders += count

					if leaderId != 0 {
						conn.leaderId = leaderId
					}
				}
			}
		}
	}
}
func StartZeromqProtobufTest(address string, clients int, requestsPerClient int, messageSize int, timer metrics.Timer, requestSize *int) func(wg *sync.WaitGroup) {
	return func(wg *sync.WaitGroup) {
		var socket *zmq.Socket
		var err error
		var request []byte

		if socket, err = zmq.NewSocket(zmq.REQ); err != nil {
			log.Fatal(err)
		}

		defer socket.Close()
		defer wg.Done()

		if err = socket.Connect("tcp://" + address); err != nil {
			log.Fatal(err)
		}

		if request, err = proto.Marshal(&pb.Request{
			Method:  "TEST",
			Payload: strings.Repeat("a", messageSize),
		}); err != nil {
			log.Fatal(err)
		}

		*requestSize = len(request)

		for i := 0; i < requestsPerClient; i++ {
			timer.Time(func() {
				socket.SendBytes(request, 0)

				socket.Recv(0)
			})
		}
	}
}
Пример #3
0
// 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
}
Пример #4
0
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)
	}
}
Пример #5
0
// ZmqRecvMulti Receives a multi-part message and return it as a slice of strings
func ZmqRecvMulti(s *zmq.Socket) []string {
	var msg []string
	more := true
	for more {
		part, _ := s.Recv(0)
		msg = append(msg, part)
		more, _ = s.GetRcvmore()
	}
	return msg
}
/******************************************************************************
* 概述:    订阅退订
* 函数名:    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
}
Пример #7
0
// serveZMQ
func serveZMQ(zmqPort int, channelStr chan string, metrics metricContainer) {

	var zmqListener *zmq.Socket

	if channelStr == nil {
		listenerURL := "*:" + strconv.Itoa(zmqPort)
		fmt.Println("ZeroMQ listening on port: " + listenerURL)
		zmqListener, _ = zmq.NewSocket(zmq.PULL)
		defer zmqListener.Close()
		zmqListener.Bind("tcp://" + listenerURL)
	}

	for {

		var msg string
		if channelStr == nil {
			//  Wait for next request from client
			var err error
			msg, err = zmqListener.Recv(0)
			if err != nil {
				fmt.Printf("Error in receive: %v", err)
				break
			}
		} else {
			msg = <-channelStr
		}

		// unmarshall bulked data
		var bulk []string
		err := json.Unmarshal([]byte(msg), &bulk)
		if err != nil {
			fmt.Println("json unmarshall error:", err)
		}

		// extra data
		for _, data := range bulk {

			dtime, _ := utils.ParseDate4(data[:19])
			//dtime, err := time.Parse(dtFormat, data[:19]) // date time
			if err != nil {
				fmt.Println("time.Parse error:", err)
			}

			value := data[20:]
			intval, _ := strconv.Atoi(value)
			m := metric{dtime, intval}
			metrics.AddMetric(&m)
			//fmt.Println("At ", dtime, " value=", value)

		}

	}

}
Пример #8
0
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
}
Пример #9
0
// 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
}
Пример #10
0
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")
	}
}
Пример #11
0
func receiveMessage(recSockets *zmq.Socket, conn *Connection) {

	for {
		//		var msg string

		select {
		case _, _ = <-conn.stopGoRoutine:

			fmt.Println("Stopping Go Routine")

			//close(conn.stopGoRoutine)
			return

		default:

			msg, _ := recSockets.Recv(0)
			fmt.Println("Msg Recv :- ", msg)

			//msg_seq:IsLeader:LeaderId:SelfId
			msg_array := strings.Split(msg, ":")

			msg_seq := msg_array[0]
			isLeader := msg_array[1]
			leaderId, _ := strconv.Atoi(msg_array[2])
			//senderId := msg_array[3]

			count, _ := strconv.Atoi(isLeader)

			// Added the LeaderCount if the response belongs to corresponding request
			if strconv.Itoa(conn.attempt) == msg_seq {
				conn.recvCount += 1
				conn.leaders += count

				if leaderId != 0 {
					conn.leaderId = leaderId
					fmt.Println("Leader Id :- ", conn.leaderId)
				}
			}
		}
	}
}
Пример #12
0
/****************************************************************
	Receiving Message from all Servers
****************************************************************/
func receiveMessage(recSockets *zmq.Socket, conn *Connection) {
	fmt.Println("In Received")
	for {
		select {
		// Stopping Go Routine
		case _, _ = <-conn.stopGoRoutine:
			return

		default:
			recSockets.SetRcvtimeo(500 * time.Millisecond)
			msg, err := recSockets.Recv(0)

			if err == nil {

				//fmt.Println("Received :- ",msg)

				conn.receivedMessage <- msg
			}
		}
	}
}
Пример #13
0
func RecieveClientRequest(receiver *zmq.Socket, myservices map[string]ProcessRequest) (service_required ProcessRequest, message string, err error) {
	for count := 0; ; count++ {
		var request string
		request, err = receiver.Recv(0)
		if err != nil {
			err = errors.New(fmt.Sprintf("Error:Receive:%s", err))
			return
		}
		fmt.Println("\tCurrent: ", request)
		//  Retrieve message parts from the envelope
		//  The first part is either:
		//  a. A heartbeat request
		//  b. The service's SID
		//  The second part: the message
		if count == 0 {
			var isPresent bool
			service_required, isPresent = myservices[request]
			fmt.Printf("%s is present? %s", request, isPresent)
			if !isPresent {
				err = errors.New("Error:InvalidService")
				return
			}
		}
		if count == 1 {
			message = request
		}
		//  Check if there are more in envelope and deal with any errors
		var more bool
		more, err = receiver.GetRcvmore()
		if err != nil {
			err = errors.New(fmt.Sprintf("Error:Receive:%s", err))
			return
		}
		if !more {
			return
		}
	}
}
Пример #14
0
func dump(soc *zmq.Socket) {
	fmt.Println("----------------------------------------")
	for {
		//  Process all parts of the message
		message, _ := soc.Recv(0)

		//  Dump the message as text or binary
		fmt.Printf("[%03d] ", len(message))
		if all_char.MatchString(message) {
			fmt.Print(message)
		} else {
			for i := 0; i < len(message); i++ {
				fmt.Printf("%02X ", message[i])
			}
		}
		fmt.Println()

		more, _ := soc.GetRcvmore()
		if !more {
			break
		}
	}
}
Пример #15
0
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)
}
Пример #16
0
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)
	}
}
Пример #17
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)
	}
}
Пример #18
0
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
}
Пример #19
0
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)
	}
}
Пример #20
0
//  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
}
Пример #21
0
// 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
	}
}
Пример #22
0
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
}
Пример #23
0
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
	}

}
Пример #24
0
func serveFrontend(frontend *zmq.Socket) (back *zmq.Socket) {
	var header []string
	var service Service
	isPresent := false
	//fmt.Println("\nReceiving message from client...")
	for {
		msg, _ := frontend.Recv(0)
		//fmt.Printf("\tIn-->%s\n", msg)
		message := strings.SplitN(msg, ":", 2)
		if more, _ := frontend.GetRcvmore(); more {
			//  If this part of the message contains no service description
			//  treat is as a header
			if len(message) != 2 {
				header = append(header, msg)
				continue
			}

			//  If the service request is to register a service, register it
			if message[0] == "register" {
				back = registerService(message[1], header, frontend)
				return
			}

			//  If the service requested is not in the service list then assume
			//  it will be at end of message and treat message as part of header
			service, isPresent = services[message[0]]
			if !isPresent {
				header = append(header, msg)
				continue
			}

			//  If the service requested is available send the early parts of
			//  message at this point
			for key := range header {
				//fmt.Printf("\tForwarding to %s at %s: %s\n", service.Name, service.Address, header[key])
				service.Backend.Send(header[key], zmq.SNDMORE)
			}
			header = header[:0] // Empty header to avoid accidental resend below
			service.Backend.Send(message[1], zmq.SNDMORE)
		} else {
			// If the service request is to register a service, register it
			if message[0] == "register" {
				back = registerService(message[1], header, frontend)
				return
			}

			// Has the service already been discovered? -If not, discover it
			if !isPresent {
				service, isPresent = services[message[0]]
			}

			//  If the service is still not discovered at this point, then we
			//   have a problem. Report back to client
			if !isPresent {
				sendToClient("InvalidService", header, "Invalid Service SID", 0, frontend)
				break
			}

			//  Otherwise everything is good fetch the service and send request
			//  Send the assumed header of the message
			for key := range header {
				//fmt.Printf("\tForwarding to %s at %s: %s\n", service.Name, service.Address, header[key])
				service.Backend.Send(header[key], zmq.SNDMORE)
			}
			//  Send the rest of the message
			//fmt.Printf("\tForwarding to %s at %s: %s\n", service.Name, service.Address, message[1])
			service.Backend.Send(message[1], 0)
			//fmt.Println("\tDone")
			break
		}
	}
	return
}
/******************************************************************************
* 概述:    接收处理推送信息
* 函数名:    dealSub
* 返回值:
* 参数列表:  参数名          参数类型      取值范围     描述
*
*******************************************************************************/
func (this *ZmqSocket) dealSub(soc *zmq4.Socket, msgHeadFlag *bool) error {
	//	log4.Debug("start deal sub0...")
	//	this.mchooseMutex.RLocker()
	if !this.mChoose {
		//	this.mchooseMutex.RUnlock()
		return nil
	}
	log4.Debug("start deal sub...")
	//	this.mchooseMutex.RUnlock()
	for {
		if *msgHeadFlag {
			topic, err := soc.Recv(zmq4.DONTWAIT)
			if err != nil {
				errno1 := zmq4.AsErrno(err)
				switch errno1 {
				case zmq4.Errno(syscall.EAGAIN):
					return nil
				case zmq4.Errno(syscall.EINTR):
					continue
				default:
					log4.Debug("zmq req Get err %v, %d!", errno1, errno1)
				}
			}
			if len(topic) == 0 {
				//				log4.Debug("sub return1")
				return nil
			}
			//			log4.Debug("recv sub head =", topic)
			*msgHeadFlag = false
		} else {
			stream, err2 := soc.RecvBytes(zmq4.DONTWAIT)
			if err2 != nil {
				errno1 := zmq4.AsErrno(err2)
				switch errno1 {
				case zmq4.Errno(syscall.EAGAIN):
					return nil
				case zmq4.Errno(syscall.EINTR):
					continue
				default:
					log4.Debug("zmq req Get err %v, %d!", errno1, errno1)
				}
			}
			if len(stream) == 0 {
				//				log4.Debug("sub return2")
				return nil
			}
			*msgHeadFlag = true

			frm, err3 := common.UnwrapBaseProto(stream)
			if err3 != nil {
				log4.Error("UnwrapBaseProto falied, %s", err3.Error())
				return err3
			}

			mid := common.UnOffset(*frm.GetBody().Mid, 4)
			if mid[4-1] == 200 {
				log4.Error("sdssdk zmqsub get mid == 200 err")
				continue
			}
			res, err4 := common.UnwrapResponse(frm.GetBody().Mdata)
			if err4 != nil {
				log4.Error("sdssdk sub UnwrapResponse error:", err4)
				continue
			}
			this.mzmq.MdataCache.UpdatePoints(res)
		}
	}
	return nil
}
Пример #26
0
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
	}

}