Esempio n. 1
0
func main() {
	arg := "server"
	if len(os.Args) > 1 {
		arg = os.Args[1]
	}
	log.Info("=[%s\n]===================================================================", arg)

	path := os.Getenv("GOPATH")
	fmt.Println(path)

	path = os.Getenv("GOROOT")
	fmt.Println(path)

	syscall_path, ok := syscall.Getenv("_system_arch")
	fmt.Println(syscall_path)
	fmt.Println(ok)

	path = os.Getenv("_system_name")
	fmt.Println(path)

	if arg == "server" || arg == "" {
		log.Info("run server!")
		context, _ := zmq.NewContext()
		socket, _ := context.NewSocket(zmq.REP)
		socket.Bind("tcp://127.0.0.1:5000")
		socket.Bind("tcp://127.0.0.1:6000")

		for {
			msg, _ := socket.Recv(0)
			println("Got", string(msg))
			socket.Send(msg, 0)
		}
	} else if arg == "client" {
		log.Info("client server!")
		context, _ := zmq.NewContext()
		socket, _ := context.NewSocket(zmq.REQ)
		socket.Connect("tcp://127.0.0.1:5000")
		socket.Connect("tcp://127.0.0.1:6000")

		for i := 0; i < 10; i++ {
			msg := fmt.Sprintf("msg %d", i)
			socket.Send([]byte(msg), 0)
			println("Sending", msg)
			socket.Recv(0)
		}
	}

}
Esempio n. 2
0
func main() {

	// Initialize publisher
	pub := entity.Publisher{}
	pub.AppendAddress("tcp://*:6602")

	context, _ := zmq.NewContext()
	defer context.Close()

	if err := pub.InitialBinding(context); err != nil {
		log.Fatalln("Initialize publisher failure.", err)
	}

	value := example.Test{}
	value.Label = proto.String("value1")
	value.Type = proto.Int32(0)

	for {
		time.Sleep(time.Second)
		*value.Type = value.GetType() + 2
		if err := pub.Write(&value); err != nil {
			log.Println("Publish value failure.")
		} else {
			log.Println("Publish value okay.")
		}
	}

}
Esempio n. 3
0
func main() {
	file, err := ioutil.ReadFile("./config.json")
	if err != nil {
		fmt.Printf("File error: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("%s\n", file)

	config := SensuConfig{}
	json.Unmarshal(file, &config)
	fmt.Printf("Config: %v\n", config)

	context, _ := zmq.NewContext()
	socket, _ := context.NewSocket(zmq.REQ)

	for _, server := range config.Servers {
		uri := fmt.Sprintf("tcp://%s:%d", server.Host, server.Port)
		fmt.Printf("Connecting to server: %s\n", uri)
		socket.Connect(uri)
	}

	cmd := exec.Command("echo", "-n", "foo")
	output, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Printf("Command error: %v\n", err)
	}
	cmd.Wait()
	fmt.Printf("Command output: %s\n", output)
}
Esempio n. 4
0
func main() {
	context, _ := zmq.NewContext()
	socket, _ := context.NewSocket(zmq.PUB)
	defer context.Close()
	defer socket.Close()
	socket.Bind("tcp://*:5556")
	socket.Bind("ipc://weather.ipc")

	// Seed the random number generator
	rand.Seed(time.Now().UnixNano())

	// loop for a while aparently
	for {

		//  make values that will fool the boss
		zipcode := rand.Intn(100000)
		temperature := rand.Intn(215) - 80
		relhumidity := rand.Intn(50) + 10

		msg := fmt.Sprintf("%d %d %d", zipcode, temperature, relhumidity)

		//  Send message to all subscribers
		socket.Send([]byte(msg), 0)
	}
}
Esempio n. 5
0
func client_task(c chan string) {
	context, _ := zmq.NewContext()
	client, _ := context.NewSocket(zmq.DEALER)
	defer context.Close()
	defer client.Close()

	client.SetIdentity("C")
	client.Connect("tcp://localhost:5555")

	fmt.Println("Setting up test...")
	time.Sleep(time.Duration(100) * time.Millisecond)

	fmt.Println("Synchronous round-trip test...")
	start := time.Now()
	requests := 10000
	for i := 0; i < requests; i++ {
		client.Send([]byte("hello"), 0)
		client.Recv(0)
	}
	fmt.Printf("%d calls/second\n", int64(float64(requests)/time.Since(start).Seconds()))

	fmt.Println("Asynchronous round-trip test...")
	start = time.Now()
	for i := 0; i < requests; i++ {
		client.Send([]byte("hello"), 0)
	}
	for i := 0; i < requests; i++ {
		client.Recv(0)
	}
	fmt.Printf("%d calls/second\n", int64(float64(requests)/time.Since(start).Seconds()))

	c <- "done"
}
Esempio n. 6
0
// createSockets initializes the sockets for the socket group based on values from zmq.
func createSockets() (*zmq.Context, SocketGroup, error) {

	context, err := zmq.NewContext()
	if err != nil {
		return context, SocketGroup{}, errors.Wrap(err, "Could not create zmq Context")
	}

	var sg SocketGroup
	sg.ShellSocket, err = context.NewSocket(zmq.ROUTER)
	if err != nil {
		return context, sg, errors.Wrap(err, "Could not get Shell Socket")
	}

	sg.ControlSocket, err = context.NewSocket(zmq.ROUTER)
	if err != nil {
		return context, sg, errors.Wrap(err, "Could not get Control Socket")
	}

	sg.StdinSocket, err = context.NewSocket(zmq.ROUTER)
	if err != nil {
		return context, sg, errors.Wrap(err, "Could not get Stdin Socket")
	}

	sg.IOPubSocket, err = context.NewSocket(zmq.PUB)
	if err != nil {
		return context, sg, errors.Wrap(err, "Could not get IOPub Socket")
	}

	return context, sg, nil
}
Esempio n. 7
0
func Startmaster(data Interfacemaster) {
	var queries_file = flag.String("q", "", "queries file")
	var index_file = flag.String("i", "", "index file")
	flag.Parse()

	// ventilator
	context, _ := zmq.NewContext()
	defer context.Close()

	sender, _ := context.NewSocket(zmq.PUSH)
	defer sender.Close()
	sender.Bind("tcp://*:5557")
	fmt.Println("Sending tasks to workers...")

	//Sink
	receiver, _ := context.NewSocket(zmq.PULL)
	defer receiver.Close()
	receiver.Bind("tcp://*:5558")

	vent_quit := make(chan int)
	if *queries_file != "" && *index_file != "" {
		f, err := os.Open(*queries_file)
		if err != nil {
			panic("error opening file " + *queries_file)
		}
		r := bufio.NewReader(f)
		go func() {
			count := 0
			for {
				line, err := r.ReadBytes('\n')
				if err != nil {
					break
				}
				if len(line) > 1 {
					msg := data.ProduceMsg(line, count, *index_file)
					sender.Send(msg, 0)
				}
				count++
			}
			vent_quit <- count
		}()
	}

	read_count := 0
	result_count := 0

	// receving results from workers
	for result_count < read_count || read_count <= 0 {
		select {
		case read_count = <-vent_quit:
			break
		default:
			break
		}
		msgbytes, _ := receiver.Recv(0)
		result_count++

		data.AnalyzeResult(msgbytes)
	}
}
Esempio n. 8
0
func newBroker(endpoint string, heartbeatIntv, workerExpiry time.Duration) (broker Broker, err error) {
	context, err := zmq.NewContext()
	if err != nil {
		return
	}
	socket, err := context.NewSocket(zmq.ROUTER)
	if err != nil {
		return
	}
	err = socket.SetSockOptInt(zmq.LINGER, 0)
	if err != nil {
		return
	}
	err = socket.Bind(endpoint)
	if err != nil {
		return
	}
	broker = &mdBroker{
		context:       context,
		services:      make(map[string]*mdService),
		socket:        socket,
		waiting:       NewList(),
		workers:       make(map[string]*refWorker),
		heartbeatAt:   time.Now().Add(heartbeatIntv),
		heartbeatIntv: heartbeatIntv,
		workerExpiry:  workerExpiry,
		errors:        make(chan error),
	}
	return
}
Esempio n. 9
0
func main() {
	context, _ := zmq.NewContext()
	defer context.Close()

	//  Connect our subscriber socket
	subscriber, _ := context.NewSocket(zmq.SUB)
	defer subscriber.Close()
	subscriber.SetSockOptString(zmq.IDENTITY, "Hello")
	subscriber.SetSockOptString(zmq.SUBSCRIBE, "")
	subscriber.Connect("tcp://localhost:5565")

	//  Synchronize with publisher
	sync, _ := context.NewSocket(zmq.PUSH)
	defer sync.Close()
	sync.Connect("tcp://localhost:5564")
	sync.Send([]byte{}, 0)

	//  Get updates, expect random Ctrl-C death
	for {
		data, _ := subscriber.Recv(0)
		str := string(data)
		println(str)
		if str == "END" {
			break
		}
	}
}
Esempio n. 10
0
func bindingPub(addr Address, t *testing.T) {

	inst := Publisher{}
	inst.Addr = make([]Address, 1)
	inst.Addr[0] = addr

	err := make(chan error)
	context, _ := zmq.NewContext()
	defer context.Close()

	// select {
	// case err <- inst.InitialBinding(context):
	// 	if err != nil {
	// 		t.Errorf("Address should bind on %s, while return %s",
	// 			string(inst.Addr[0]), err)
	// 	}
	// case <-time.After(time.Second):
	// 	return
	// }
	if err <- inst.InitialBinding(context); err != nil {
		t.Errorf("Address should bind on %s, while return %s\n",
			string(inst.Addr[0]), <-err)
	}

}
Esempio n. 11
0
func main() {
	context, _ := zmq.NewContext()
	defer context.Close()

	// Socket to talk to clients
	publisher, _ := context.NewSocket(zmq.PUB)
	defer publisher.Close()
	publisher.Bind("tcp://*:5561")

	// Socket to receive signals
	syncservice, _ := context.NewSocket(zmq.REP)
	defer syncservice.Close()
	syncservice.Bind("tcp://*:5562")

	// Get synchronization from subscribers
	for i := 0; i < subsExpected; i = i + 1 {
		syncservice.Recv(0)
		syncservice.Send([]byte(""), 0)
	}

	for update_nbr := 0; update_nbr < 1000000; update_nbr = update_nbr + 1 {
		publisher.Send([]byte("Rhubarb"), 0)
	}

	publisher.Send([]byte("END"), 0)
}
Esempio n. 12
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])
		}
	}
}
Esempio n. 13
0
func main() {
	context, _ := zmq.NewContext()
	publisher, _ := context.NewSocket(zmq.PUB)
	defer publisher.Close()
	publisher.Bind(chatroom.PUBLISHER_ADDRESS)

	router, _ := context.NewSocket(zmq.PULL)
	defer router.Close()
	router.Bind(chatroom.POST_ADDRESS)

	stat_channel := make(chan int)
	go admin_server(stat_channel)

	receiver_channel := bind_to_channel(router)

	for {
		select {
		case msg := <-receiver_channel:
			go func() {
				stat_channel <- 1
				publisher.Send(msg, 0)
			}()
		}
	}
}
Esempio n. 14
0
func main() {
	context, _ := zmq.NewContext()
	defer context.Close()

	client, _ := context.NewSocket(zmq.ROUTER)
	defer client.Close()
	client.Bind("ipc://routing.ipc")

	rand.Seed(time.Now().Unix())

	for i := 0; i < NBR_WORKERS; i++ {
		go workerTask()
	}

	for i := 0; i < NBR_WORKERS*10; i++ {
		//  LRU worker is next waiting in queue
		parts, err := client.RecvMultipart(0)
		if err != nil {
			print(err)
		}
		address := parts[0]
		client.SendMultipart([][]byte{address, []byte(""), []byte("This is the workload")}, 0)
	}

	//  Now ask mamas to shut down and report their results
	for i := 0; i < NBR_WORKERS; i++ {
		parts, err := client.RecvMultipart(0)
		if err != nil {
			print(err)
		}
		address := parts[0]
		client.SendMultipart([][]byte{address, []byte(""), []byte("END")}, 0)
	}
}
Esempio n. 15
0
func workerTask() {
	context, _ := zmq.NewContext()
	defer context.Close()

	worker, _ := context.NewSocket(zmq.REQ)
	worker.SetSockOptString(zmq.IDENTITY, randomString())

	worker.Connect("ipc://routing.ipc")
	defer worker.Close()

	var total int
	for {
		err := worker.Send([]byte("ready"), 0)
		if err != nil {
			print(err)
		}
		data, _ := worker.Recv(0)
		if string(data) == "END" {
			id, _ := worker.GetSockOptString(zmq.IDENTITY)
			fmt.Printf("Processed: %2d tasks (%s)\n", total, id)
			break
		}
		total += 1

		msec := rand.Intn(1000)
		time.Sleep(time.Duration(msec) * time.Millisecond)
	}
}
Esempio n. 16
0
func main() {
	context, _ := zmq.NewContext()
	defer context.Close()

	//  Socket to receive messages on
	receiver, _ := context.NewSocket(zmq.PULL)
	defer receiver.Close()
	receiver.Connect("tcp://localhost:5557")

	//  Socket to send messages to task sink
	sender, _ := context.NewSocket(zmq.PUSH)
	defer sender.Close()
	sender.Connect("tcp://localhost:5558")

	//  Process tasks forever
	for {
		msgbytes, _ := receiver.Recv(0)
		fmt.Printf("%s.\n", string(msgbytes))

		//  Do the work
		msec, _ := strconv.ParseInt(string(msgbytes), 10, 64)
		time.Sleep(time.Duration(msec) * 1e6)

		//  Send results to sink
		sender.Send([]byte(""), 0)

	}
}
Esempio n. 17
0
func main() {

	flag.Parse()
	// set the logger and log level
	SetLogger(log.New(os.Stdout, "", log.Ltime|log.Lshortfile), *logLevel)

	// make a go channel for msgs
	stream := make(chan []byte, 200)
	done := make(chan bool)

	// the stream listener effectively operates in one "thread"
	client := NewBasicAuthClient(*user, *pwd, func(line []byte) {
		stream <- line
	})

	go func() {
		_ = client.Sample(done)

		context, _ := zmq.NewContext()
		socket, _ := context.NewSocket(zmq.PUB) // PUSH?
		socket.Bind(*sink)
		defer func() {
			context.Close()
			socket.Close()
		}()
		for {
			evt := <-stream
			socket.Send(evt, 0)
		}
	}()

	_ = <-done

}
Esempio n. 18
0
// Handles the setup of the various variables, and the startup of the
// main relay loop.
func RunAnnouncer() {

	context, zmqContextError := gozmq.NewContext()
	if zmqContextError != nil {
		errorHandler("zmqContextError:", zmqContextError.Error())
	}

	listener, listenSocketError := context.NewSocket(gozmq.SUB)
	if listenSocketError != nil {
		errorHandler("listenSocketError", listenSocketError.Error())
	}

	// This ZeroMQ socket is what we receive incoming messages on.
	listener.SetSockOptString(gozmq.SUBSCRIBE, "")

	listener.Bind("tcp://0.0.0.0:8049")

	// This ZeroMQ socket is where we relay the messages back out over.
	sender, senderSocketError := context.NewSocket(gozmq.PUB)
	if senderSocketError != nil {
		errorHandler("senderSocketError", senderSocketError.Error())
	}

	sender.Bind("tcp://0.0.0.0:8050")

	// Let's get this party started.
	announcerLoop(listener, sender)
}
Esempio n. 19
0
func main() {
	context, _ := zmq.NewContext()
	socket, _ := context.NewSocket(zmq.SUB)
	defer context.Close()
	defer socket.Close()

	var temps []string
	var err error
	var temp int64
	total_temp := 0
	filter := "59937"

	// find zipcode
	if len(os.Args) > 1 { // ./wuclient 85678
		filter = string(os.Args[1])
	}

	//  Subscribe to just one zipcode (whitefish MT 59937)
	fmt.Printf("Collecting updates from weather server for %s…\n", filter)
	socket.SetSubscribe(filter)
	socket.Connect("tcp://localhost:5556")

	for i := 0; i < 101; i++ {
		// found temperature point
		datapt, _ := socket.Recv(0)
		temps = strings.Split(string(datapt), " ")
		temp, err = strconv.ParseInt(temps[1], 10, 64)
		if err == nil {
			// Invalid string
			total_temp += int(temp)
		}
	}

	fmt.Printf("Average temperature for zipcode %s was %dF \n\n", filter, total_temp/100)
}
Esempio n. 20
0
func worker_task() {
	context, _ := zmq.NewContext()
	defer context.Close()

	worker, _ := context.NewSocket(zmq.DEALER)
	defer worker.Close()
	worker.SetIdentity(randomString())
	worker.Connect("tcp://localhost:5671")

	total := 0
	for {
		//  Tell the broker we're ready for work
		worker.SendMultipart([][]byte{[]byte(""), []byte("Hi Boss")}, 0)

		//  Get workload from broker, until finished
		parts, _ := worker.RecvMultipart(0)
		workload := parts[1]
		if string(workload) == "Fired!" {
			id, _ := worker.Identity()
			fmt.Printf("Completed: %d tasks (%s)\n", total, id)
			break
		}
		total++

		//  Do some random work
		time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
	}
}
Esempio n. 21
0
func main() {
	context, _ := zmq.NewContext()
	defer context.Close()

	//  Socket to receive messages on
	receiver, _ := context.NewSocket(zmq.PULL)
	defer receiver.Close()
	receiver.Bind("tcp://*:5558")

	//  Wait for start of batch
	msgbytes, _ := receiver.Recv(0)
	fmt.Println("Received Start Msg ", string(msgbytes))

	//  Start our clock now
	start_time := time.Now().UnixNano()

	//  Process 100 confirmations
	for i := 0; i < 100; i++ {
		msgbytes, _ = receiver.Recv(0)
		fmt.Print(".")
	}

	//  Calculate and report duration of batch
	te := time.Now().UnixNano()
	fmt.Printf("Total elapsed time: %d msec\n", (te-start_time)/1e6)

}
Esempio n. 22
0
func main() {
	context, _ := zmq.NewContext()
	defer context.Close()

	//  Subscriber tells us when it's ready here
	sync, _ := context.NewSocket(zmq.PULL)
	defer sync.Close()
	sync.Bind("tcp://*:5564")

	//  We send updates via this socket
	publisher, _ := context.NewSocket(zmq.PUB)
	defer publisher.Close()
	publisher.Bind("tcp://*:5565")

	//  Wait for synchronization request
	sync.Recv(0)

	for update_nbr := 0; update_nbr < 10; update_nbr++ {
		str := fmt.Sprintf("Update %d", update_nbr)
		publisher.Send([]byte(str), 0)
		time.Sleep(1e9)
	}
	publisher.Send([]byte("END"), 0)

	time.Sleep(1)
}
Esempio n. 23
0
func main() {
	src := rand.NewSource(time.Now().UnixNano())
	random := rand.New(src)

	context, _ := zmq.NewContext()
	defer context.Close()

	server, _ := context.NewSocket(zmq.REP)
	defer server.Close()
	server.Bind(SERVER_ENDPOINT)

	for cycles := 1; ; cycles++ {
		request, _ := server.Recv(0)

		//  Simulate various problems, after a few cycles
		if cycles > 3 {
			switch r := random.Intn(3); r {
			case 0:
				fmt.Println("I: Simulating a crash")
				return
			case 1:
				fmt.Println("I: simulating CPU overload")
				time.Sleep(2 * time.Second)
			}
		}
		fmt.Printf("I: normal request (%s)\n", request)
		time.Sleep(1 * time.Second) //  Do some heavy work
		server.Send(request, 0)
	}
}
Esempio n. 24
0
func send10() error {
	context, err := zmq.NewContext()
	if err != nil {
		return err
	}

	socket, err := context.NewSocket(zmq.REQ)
	if err != nil {
		return err
	}

	if err := socket.Connect("tcp://127.0.0.1:1234"); err != nil {
		return err
	}

	if err := socket.Connect("tcp://127.0.0.1:5678"); err != nil {
		return err
	}

	for i := 0; i < 10; i++ {
		msg := fmt.Sprintf("msg %d", i)

		err := socket.Send([]byte(msg), 0)
		if err != nil {
			return err
		}

		_, err = socket.Recv(0)
		if err != nil {
			return err
		}
	}

	return nil
}
Esempio n. 25
0
func broker_task() {
	context, _ := zmq.NewContext()
	frontend, _ := context.NewSocket(zmq.ROUTER)
	backend, _ := context.NewSocket(zmq.ROUTER)
	defer context.Close()
	defer frontend.Close()
	defer backend.Close()
	frontend.Bind("tcp://*:5555")
	backend.Bind("tcp://*:5556")

	// Initialize poll set
	items := zmq.PollItems{
		zmq.PollItem{Socket: frontend, Events: zmq.POLLIN},
		zmq.PollItem{Socket: backend, Events: zmq.POLLIN},
	}

	for {
		zmq.Poll(items, -1)
		switch {
		case items[0].REvents&zmq.POLLIN != 0:
			msg, _ := frontend.RecvMultipart(0)
			msg[0][0] = 'W'
			backend.SendMultipart(msg, 0)
		case items[1].REvents&zmq.POLLIN != 0:
			msg, _ := backend.RecvMultipart(0)
			msg[0][0] = 'C'
			frontend.SendMultipart(msg, 0)
		}
	}
}
Esempio n. 26
0
func loop(cfg *Configuration) {
	context, err := zmq.NewContext()
	check_err(err, "ZMQ Context error: %v")
	socket, err := context.NewSocket(zmq.REQ)
	check_err(err, "ZMQ Socket error: %v")
	defer context.Close()
	defer socket.Close()
	log.Printf("Connect to %s", cfg.Url())
	socket.Connect(cfg.Url())

	for {
		request := &itpkg_protocols.Request{
			Nid:     proto.String(cfg.Nid),
			Type:    &itpkg_protocols.Type(0),
			Created: proto.Int64(time.Now().Unix())}
		msg, err := proto.Marshal(request)
		check_err(err, "GPF generate error: %v")
		socket.Send([]byte(msg), 0)
		log.Printf("Sending %v", request)

		reply, err := socket.Recv(0)
		check_err(err, "Recv error")
		response := &itpkg_protocols.Response{}
		err = proto.Unmarshal(reply, response)
		check_err(err, "GPF parse error: %v")

		log.Printf("Received %s", string(reply))
	}
}
Esempio n. 27
0
func main() {
	context, _ := zmq.NewContext()
	defer context.Close()

	frontend, _ := context.NewSocket(zmq.ROUTER)
	backend, _ := context.NewSocket(zmq.DEALER)
	defer frontend.Close()
	defer backend.Close()
	frontend.Bind("tcp://*:5559")
	backend.Bind("tcp://*:5560")

	// Initialize poll set
	toPoll := zmq.PollItems{
		zmq.PollItem{Socket: frontend, Events: zmq.POLLIN},
		zmq.PollItem{Socket: backend, Events: zmq.POLLIN},
	}

	for {
		_, _ = zmq.Poll(toPoll, -1)

		switch {
		case toPoll[0].REvents&zmq.POLLIN != 0:
			parts, _ := frontend.RecvMultipart(0)
			backend.SendMultipart(parts, 0)

		case toPoll[1].REvents&zmq.POLLIN != 0:
			parts, _ := backend.RecvMultipart(0)
			frontend.SendMultipart(parts, 0)
		}
	}
}
Esempio n. 28
0
func RunZmq(pub, sub string, handler func(string)) func(string) {

	context, _ := zmq.NewContext()
	defer context.Close()

	socketPub, _ := context.NewSocket(zmq.PUB)
	defer socketPub.Close()
	socketPub.Bind(pub)
	println("starting zmq publisher on ", pub)

	socketSub, _ := context.NewSocket(zmq.SUB)
	defer socketSub.Close()
	// connect with no subscription filter
	socketSub.Connect(sub)
	socketSub.SetSockOptString(zmq.SUBSCRIBE, "")

	println("starting zmq subscriber on ", sub)

	go func() {
		for {
			// block here, waiting for inbound requests
			msg, _ := socketSub.Recv(0)
			handler(string(msg))
		}
	}()

	return func(msg string) {
		socketPub.Send([]byte(msg), 0)
	}
}
Esempio n. 29
0
func workerTask() {
	context, _ := zmq.NewContext()
	defer context.Close()

	worker, _ := context.NewSocket(zmq.REQ)
	worker.SetSockOptString(zmq.IDENTITY, randomString())

	worker.Connect("tcp://localhost:5671")
	defer worker.Close()

	total := 0
	for {
		err := worker.Send([]byte("Hi Boss"), 0)
		if err != nil {
			print(err)
		}
		workload, _ := worker.Recv(0)
		if string(workload) == "Fired!" {
			id, _ := worker.GetSockOptString(zmq.IDENTITY)
			fmt.Printf("Completed: %d tasks (%s)\n", total, id)
			break
		}

		total += 1
		msec := rand.Intn(1000)
		time.Sleep(time.Duration(msec) * time.Millisecond)
	}
}
Esempio n. 30
0
func main() {
	context, _ := zmq.NewContext()
	insocket, _ := context.NewSocket(zmq.PULL)
	outsocket, _ := context.NewSocket(zmq.ROUTER)
	defer context.Close()
	defer insocket.Close()
	insocket.Connect("ipc://run/slow")
	outsocket.Connect("ipc://run/slow_response")
	const passphrase = "my_shared_secret"
	//test_msg := " 36:4d80af85-5e31-4322-9b27-8e9fbb5ae69f 13:1358433619512 16:my_shared_secret 36:34f9ceee-cd52-4b7f-b197-88bf2f0ec378 1:1 20:tcp://127.0.0.1:9998 13:/service/slow 7:request 75:{\"RETURN_DATA\":\"I made a round trip, it took a while but I bring results.\"}2:{}2:{}"
	//var request_fields, err = parse_service_request(test_msg)
	//if err == nil {
	//    handle_request(createBrubeckServiceRequest(request_fields), outsocket)
	//}

	println("Go Brubeck Service v0.1.0 online ]-----------------------------------")
	// Wait for messages
	for {
		msg, _ := insocket.Recv(0)
		var request_fields, err = parse_service_request(string(msg))
		if err == nil {
			// Pass off all responsibility to the handler
			handle_request(createBrubeckServiceRequest(request_fields), outsocket, passphrase)
		} else {
			println("ERROR: ", err)
		}
	}
}