ZeroMQ入门示例

一、一问一答模式

服务端代码:

// server.cpp
#include "./include/zmq.h"
#pragma comment(lib, "libzmq.lib")

int _tmain(int argc, _TCHAR* argv[])
{
	void *context = zmq_ctx_new();
	void *responder = zmq_socket(context, ZMQ_REP);
	int rc = zmq_bind(responder, "tcp://*:5555");
	assert(rc == 0);

	while (1) {
		char buffer[11] = { 0 };
		zmq_recv(responder, buffer, 10, 0);
		printf("Received: %s\n", buffer);

		zmq_send(responder, "World", 5, 0);
	}

	return 0;
}

客户端代码:

// client.cpp
#include "include/zmq.h"
#pragma comment(lib, "libzmq.lib")

int _tmain(int argc, _TCHAR* argv[])
{
	printf("Connecting to hello world server…\n");
	void *context = zmq_ctx_new();
	void *requester = zmq_socket(context, ZMQ_REQ);
	zmq_connect(requester, "tcp://localhost:5555");

	zmq_send(requester, "Hello", 5, 0);

	char buffer[11] = { 0 };
	zmq_recv(requester, buffer, 10, 0);
	printf("Received: %s\n", buffer);

	zmq_close(requester);
	zmq_ctx_destroy(context);

	return 0;
}

二、 消息订阅模式

消息发布者代码:

// Publisher.cpp
int _tmain(int argc, _TCHAR* argv[])
{
	void *context = zmq_ctx_new();
	void *publisher = zmq_socket(context, ZMQ_PUB);
	int rc = zmq_bind(publisher, "tcp://*:5556");
	assert(rc == 0);

	while (1) {
		// Send timestamp to all subscribers
		char timestamp[31] = { 0 };
		sprintf(timestamp, "timestamp %ld", time(NULL));
		int size = zmq_send(publisher, timestamp, 30, 0);

		Sleep(5000);
	}
	zmq_close(publisher);
	zmq_ctx_destroy(context);
	return 0;
}

消息订阅者代码:

// Subscribe.cpp
int _tmain(int argc, _TCHAR* argv[])
{
void *context = zmq_ctx_new ();
void *subscriber = zmq_socket (context, ZMQ_SUB);
int rc = zmq_connect (subscriber, "tcp://localhost:5556");
assert (rc == 0);

char *filter = "timestamp ";
rc = zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE, filter, strlen (filter));
assert (rc == 0);

char buffer[256] = {0};
int size = zmq_recv (subscriber, buffer, 255, 0);
printf("Timestamp: %s\n", buffer);

zmq_close (subscriber);
zmq_ctx_destroy (context);

return 0;
}

你可能感兴趣的:(☆,网络编程)