// SimpleHelloWorldClient does the following:
// * Creates a ZMQ_REQ socket
// * Sends a "Hello" message
// * Waits for a "World" reply
func SimpleHelloWorldClient(t *testing.T) {
	t.Logf("client starting...")

	// Create a ZMQ_REQ client using a "smart constructor".
	// See: https://godoc.org/github.com/zeromq/goczmq#NewReq

	client, err := goczmq.NewReq("tcp://localhost:5555")
	if err != nil {
		t.Fatalf("client.NewReq error: %s", err)
	}

	// Here, we make sure the socket is destroyed
	// when this function exits. While Go is a garbage
	// collected language, we're binding a C library,
	// so we need to make sure to clean up.

	defer client.Destroy()

	// Let's create a request message. GoCZMQ uses slices
	// of byte slices for messages, because they map
	// very simply to ZeroMQ "frames".

	request := [][]byte{[]byte("Hello")}

	// Send the message and check for any errors.

	err = client.SendMessage(request)
	if err != nil {
		t.Fatalf("client.SendMessage error: %s", err)
	}

	t.Logf("client.SendMessage '%s'", request)

	// Receive the reply message from the server. Note that
	// this RecvMessage() call will block forever waiting
	// for a message.

	reply, err := client.RecvMessage()
	if err != nil {
		t.Fatalf("client.RecvMessage error: %s", err)
	}

	t.Logf("client.RecvMessage: '%s'", reply)
}
示例#2
0
文件: main.go 项目: tswast/gameoflife
func main() {
	pub := os.Getenv("PUB_PORT_5000_TCP")
	if pub == "" {
		log.Fatal("Missing PUB_PORT_5000_TCP environment variable")
	}
	rep := os.Getenv("PUB_PORT_5001_TCP")
	if rep == "" {
		log.Fatal("Missing PUB_PORT_5001_TCP environment variable")
	}
	reqL.Lock()
	var err error
	req, err = goczmq.NewReq(rep)
	reqL.Unlock()
	if err != nil {
		log.Fatal("Error connecting to REP %q: %q\n", rep, err.Error())
	}

	fields[0] = cell.RandomField(128, 128)
	go func() {
		sub := goczmq.NewSubChanneler(pub, "" /* all messages, no topic filtering */)
		defer sub.Destroy()

		for msg := range sub.RecvChan {
			if len(msg) != 1 {
				log.Printf(
					"Message had unexpected number of frames: %d, want 1.\n",
					len(msg))
				continue
			}
			data := msg[0]

			pf := &cell.FieldProto{}
			if err := proto.Unmarshal(data, pf); err != nil {
				log.Printf(
					"Error unmarshalling message:\n\t%q,\n\t%#v\n",
					err.Error(),
					msg)
				continue
			}
			seq := int(pf.Seq) % cacheSize
			if seq < 0 {
				seq = seq + cacheSize
			}

			f, err := cell.FromProto(pf)
			if err != nil {
				log.Printf("Got invalid Field:\n\t%q,\n\t%#v\n", err.Error(), f)
				continue
			}

			cond.L.Lock()
			curr = seq
			fields[curr] = f
			cond.Broadcast()
			cond.L.Unlock()
		}
	}()

	http.HandleFunc("/socket", socketHandler)
	http.HandleFunc("/", viewHandler)
	http.HandleFunc("/field/", fieldHandler)
	http.ListenAndServe(":8080", nil)
}