Beispiel #1
0
func recv(c chan string, socket *zmq.Socket) {
	for {
		msg, _ := socket.Recv(0)
		fmt.Println("Pulled msg: ", string(msg))
		c <- string(msg)
	}
}
Beispiel #2
0
func zmqReceiver(s *zmq.Socket, c chan []map[string]interface{}, wg *sync.WaitGroup) {
	defer wg.Done()

	for {
		buf, err := s.Recv(0)
		if err != nil {
			log.Println("zmq.Socket.Recv():", err)
			continue
		}

		var m []map[string]interface{}
		err = json.Unmarshal(buf, &m)
		if err != nil {
			log.Println("json.Unmarshal():", err)
			continue
		}

		if !check(m) {
			log.Println("Invalid Command:", m)
			continue
		}

		select {
		case toDeliver := <-c:
			toDeliver = append(toDeliver, m...)
			c <- toDeliver
		default:
			c <- m
		}
	}
}
Beispiel #3
0
func runZmqStream() {
	var context zmq.Context
	var socket zmq.Socket

	// connect to zmq
	var err error
	if context, err = zmq.NewContext(); err != nil {
		panic("No ZMQ Context?")
	}
	defer context.Close()

	if socket, err = context.NewSocket(zmq.SUB); err != nil {
		panic("No ZMQ Socket Outbound??")
	}
	defer socket.Close()
	socket.Connect("tcp://localhost:5558")
	socket.SetSockOptString(zmq.SUBSCRIBE, "")

	for {
		// block here, waiting for inbound requests
		msg, _ := socket.Recv(0)
		if len(msg) > 0 {
			parts := strings.Split(string(msg), "\n\n")
			process(parts[0])
		}
	}
}
Beispiel #4
0
func send_and_recieve(socket zmq.Socket, in_msg []byte, id string) (res []byte, err error) {
	//		println("in_msg: ", string (in_msg))
	//	println("send ", id)
	var repeat bool
	var r0 []byte
	var err0 error

	repeat = true

	for repeat {

		socket.Send(in_msg, 0)
		//		println("ok")
		r0, err0 = socket.Recv(0)

		if r0 != nil && len(r0) == 3 {
			// это указание повторить запрос еще раз
			repeat = true
			time.Sleep(1e6)
		} else {
			repeat = false
		}
	}
	//	println("recv ", id)
	//			println("out_msg: ", string (r0))
	return r0, err0
}
Beispiel #5
0
// send a message to the zmq REQ socket
func sendMessage(reqsocket zmq.Socket, m Message) {
	var address = PUB_KEY + "." + m.Nick
	b, _ := json.Marshal(m)
	var content = b
	env := envelope{address, string(content)}
	e, _ := json.Marshal(env)
	reqsocket.Send([]byte(e), 0)
	// wait for a reply
	reqsocket.Recv(0)
}
Beispiel #6
0
func receiveZmqMessage(subsocket zmq.Socket, m *Message) error {
	// using zmq multi-part messages which will arrive
	// in pairs. the first of which we don't care about so we discard.
	address, _ := subsocket.Recv(0)
	content, _ := subsocket.Recv(0)
	if startswith(string(address), PUB_KEY) {
		// it's one that we sent out, so ignore it
		return errors.New("do not echo my own messages")
	}
	return json.Unmarshal([]byte(content), m)
}
Beispiel #7
0
// The main announcer loop. Receives incoming messages, spits them back out to
// any connected subscribers.
func announcerLoop(listener *gozmq.Socket, sender *gozmq.Socket) {

	for {
		// This blocks until something comes down the pipe.
		msg, listenRecvError := listener.Recv(0)
		if listenRecvError != nil {
			errorHandler("listenRecvError", listenRecvError.Error())
		}

		sender.Send(msg, 0)
	}
}
Beispiel #8
0
func bind_to_channel(sock zmq.Socket) (channel chan []byte) {
	channel = make(chan []byte)
	go func() {
		for {
			msg, err := sock.Recv(0)
			if err != nil {
				fmt.Println("[ERROR] die at sock.Recv:", err.Error())
				break
			}
			channel <- msg
		}
	}()
	return
}
/* handling Read/Push/Delete tasks diversion based on task-type */
func goShareZmqRep(socket *zmq.Socket) {
	var err_response string
	for {
		msg, _ := socket.Recv(0)
		message_array := strings.Fields(string(msg))
		response_bytes, axn_status := DBTasks(message_array)

		if axn_status {
			socket.Send([]byte(response_bytes), 0)
		} else {
			err_response = fmt.Sprintf("Error for request sent: %s", msg)
			socket.Send([]byte(err_response), 0)
		}
	}
}
Beispiel #10
0
func (t *TransportZmq) processControlIn(bridge_out *zmq.Socket) (ok bool) {
	var err error

RetryControl:
	msg, err := bridge_out.Recv(zmq.DONTWAIT)
	if err != nil {
		switch err {
		case syscall.EINTR:
			// Try again
			goto RetryControl
		case syscall.EAGAIN:
			// Poll lied, poll again
			return true
		}

		// Failure
		t.recv_chan <- fmt.Errorf("Pull zmq.Socket.Recv failure %s", err)
		return
	}

	switch string(msg) {
	case zmq_signal_output:
		// Start polling for send
		t.poll_items[1].Events = t.poll_items[1].Events | zmq.POLLOUT
	case zmq_signal_input:
		// If we staged a receive, process that
		if t.recv_buff != nil {
			select {
			case t.recv_bridge_chan <- t.recv_buff:
				t.recv_buff = nil

				// Start polling for receive
				t.poll_items[1].Events = t.poll_items[1].Events | zmq.POLLIN
			default:
				// Do nothing, we were asked for receive but channel is already full
			}
		} else {
			// Start polling for receive
			t.poll_items[1].Events = t.poll_items[1].Events | zmq.POLLIN
		}
	case zmq_signal_shutdown:
		// Shutdown
		return
	}

	ok = true
	return
}
Beispiel #11
0
func watchSub(global_sub_socket, global_pub_socket, local_pub_socket zmq.Socket, filename string) {
	for {
		data, _ := global_sub_socket.Recv(0)
		var msg Config
		_ = json.Unmarshal(data, &msg)
		local_config := readConfig(filename)
		if msg.Time > local_config.Time {
			body := []byte(msg.Body)
			writeConfig(filename, body)
			local_pub_socket.Send(body, 0)
		} else if msg.Time < local_config.Time {
			m, _ := json.Marshal(local_config)
			global_pub_socket.Send(m, 0)
		}
		runtime.Gosched()
	}
}
Beispiel #12
0
func watchRep(ctx zmq.Context, global_rep_socket, global_sub_socket zmq.Socket, clients *[]string, pub_address string) {
	for {
		data, _ := global_rep_socket.Recv(0)
		var req Request
		_ = json.Unmarshal(data, &req)
		if req.Type == "connect" {
			var creq ConnRequest
			json.Unmarshal(data, &creq)
			if !strSliceContains(*clients, creq.RepAddress) {
				global_sub_socket.Connect(creq.PubAddress)
				reply, _ := json.Marshal(ConnReply{pub_address, *clients})
				global_rep_socket.Send(reply, 0)
				for _, adr := range *clients {
					req_socket := openSocket(ctx, zmq.REQ, adr)
					req_socket.Send(data, 0)
					req_socket.Close()
				}
				*clients = append(*clients, creq.RepAddress)
				log.Printf("Connected: " + creq.RepAddress)
			}
		}
		runtime.Gosched()
	}
}
Beispiel #13
0
// the listen and server for mongrel, expects an address like this
// @addr = string config parameter like this:
//    m2go.ListenAndServe("tcp://127.0.0.1:9555|tcp://127.0.0.1:9556|54c6755b-9628-40a4-9a2d-cc82a816345e", handler)
func ListenAndServe(addr string, handler http.Handler) {
	var Context zmq.Context
	var SocketIn zmq.Socket
	var SocketOut zmq.Socket
	var hasExited bool
	var err error

	m2addr := strings.Split(addr, "|") //

	log.Printf("m2go serving  %s\n", addr)

	/*
	  Connection to ZMQ setup
	*/
	connect := func() {
		if Context, err = zmq.NewContext(); err != nil {
			panic("No ZMQ Context?")
		}

		// listen for incoming requests
		if SocketIn, err = Context.NewSocket(zmq.PULL); err != nil {
			panic("No ZMQ Socket?")
		}
		SocketIn.Connect(m2addr[0])

		if SocketOut, err = Context.NewSocket(zmq.PUB); err != nil {
			panic("No ZMQ Socket Outbound??")
		}
		// outbound response on a different channel
		SocketOut.SetSockOptString(zmq.IDENTITY, m2addr[2])
		//socket.SetSockOptString(zmq.SUBSCRIBE, filter)
		SocketOut.Connect(m2addr[1])
	}

	connect()

	handleResponse := func(response []byte) {
		SocketOut.Send(response, 0)
	}
	stopper := func() {
		if !hasExited {
			hasExited = true
			SocketOut.Close()
			SocketIn.Close()
			Context.Close()
		}
	}
	defer stopper()

	for {
		// each inbound request
		m2data, err := SocketIn.Recv(0)
		//log.Println(string(m2data))
		if err != nil {
			log.Println("ZMQ Socket Input accept error ", err.Error())
		} else {
			go HandleM2Request(m2data, handleResponse, handler)
		}
	}
	log.Print("after close of runner")
}