【ZeroMQ】轮询zmq_poll()的使用

注意:此时不可以用ZMQ_REP ZMQ_REQ。  因为ZMQ_REQ发送一次数据后,如果没有收到数据,不能再次发送数据。 

 

ZmqIOServer端:

#include <assert.h>
#include <iostream>
#include <tchar.h>
#include <zmq.h>
using namespace std;

#pragma comment(lib,"libzmq.lib")

void main(int argc,TCHAR*argv[])
{
	void *ctx;
	ctx = zmq_init(1);
	assert(ctx);

	void *s1;
	s1 = zmq_socket(ctx,ZMQ_PULL);
	assert(s1);

	void *s2;
	s2 = zmq_socket(ctx,ZMQ_PULL);
	assert(s2);

	zmq_bind(s1,"tcp://127.0.0.1:6000");
	zmq_bind(s2,"tcp://127.0.0.1:7000");

	while(1)
	{
		zmq_pollitem_t items[2];
		items[0].socket = s1;
		items[0].fd = 0;
		items[0].events = ZMQ_POLLIN;

		items[1].socket = s2;
		items[1].fd = 0;
		items[1].events = ZMQ_POLLIN;
		int nRet = zmq_poll(items,2,-1);
		if(0 == nRet)
			continue;

		zmq_msg_t msg;
		char re_string[20] = {0};

		if(items[0].revents > 0)
		{
			zmq_msg_init(&msg);
			zmq_recv(s1,&msg,0);
			memcpy(re_string,(char*)zmq_msg_data(&msg),zmq_msg_size(&msg));
			cout<<"Socket1 recv : "<<re_string<<endl;
			zmq_msg_close(&msg);
		}

		if(items[1].revents > 0)
		{
			zmq_msg_init(&msg);
			zmq_recv(s2,&msg,0);
			memcpy(re_string,(char*)zmq_msg_data(&msg),zmq_msg_size(&msg));
			cout<<"Socket2 recv : "<<re_string<<endl;
			zmq_msg_close(&msg);
		}
	}
	
	zmq_close(s1);
	zmq_close(s2);
	zmq_term(ctx);
}


ZmqIOClient1端:

#include <assert.h>
#include <iostream>
#include <tchar.h>
#include <zmq.h>
using namespace std;

#pragma comment(lib,"libzmq.lib")

void main(int argc,TCHAR*argv[])
{
	void *ctx;
	ctx = zmq_init(1);
	assert(ctx);

	void *s1;
	s1 = zmq_socket(ctx,ZMQ_PUSH);
	assert(s1);

	zmq_connect(s1,"tcp://127.0.0.1:6000");

	while(1)
	{
		char sd_string[20];
		cout<<"请输入sd_string:"<<endl;
		gets(sd_string);

		zmq_msg_t msg;zmq_msg_init_size(&msg,strlen(sd_string)+1);
		memcpy(zmq_msg_data(&msg),sd_string,strlen(sd_string)+1);
		zmq_send(s1,&msg,0);
		zmq_msg_close(&msg);
	}

	zmq_close(s1);
	zmq_term(ctx);
}


ZmqIOClient2端:

#include <assert.h>
#include <iostream>
#include <tchar.h>
#include <zmq.h>
using namespace std;

#pragma comment(lib,"libzmq.lib")

void main(int argc,TCHAR*argv[])
{
	void *ctx;
	ctx = zmq_init(1);
	assert(ctx);

	void *s1;
	s1 = zmq_socket(ctx,ZMQ_PUSH);
	assert(s1);

	zmq_connect(s1,"tcp://127.0.0.1:7000");

	while(1)
	{
		char sd_string[20];
		cout<<"请输入sd_string2:"<<endl;
		gets(sd_string);

		zmq_msg_t msg;
		zmq_msg_init_size(&msg,strlen(sd_string)+1);
		memcpy(zmq_msg_data(&msg),sd_string,strlen(sd_string)+1);
		zmq_send(s1,&msg,0);
		zmq_msg_close(&msg);
	}

	zmq_close(s1);
	zmq_term(ctx);
}


 

你可能感兴趣的:(String,socket,tcp)