推拉之间构建起数据的双向交互。值得注意的是,先推再拉,和先拉再推,并没有启动的先后顺序。
// pull.cpp
#include <iostream>
#include <assert.h>
#include <stdio.h>
#include <nanomsg/ipc.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef WIN32 || WIN64
#include <windows.h>
#include <time.h>
#include <thread>
#else
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>
#include <nanomsg/pubsub.h>
#include <nanomsg/pipeline.h>
const char *url = "ipc:///tmp/pipeline.ipc";
typedef struct{
int type;
char text[1024];
}buf_t;
int main ()
{## 标题
buf_t *buf = NULL;
buf = (buf_t *)malloc(sizeof(buf_t));
int sock = nn_socket (AF_SP, NN_PULL);
assert (sock >= 0);
assert (nn_bind (sock, url) >= 0);
while (1)
{
int bytes = nn_recv (sock, &buf, NN_MSG, 0);
assert (bytes >= 0);
printf ("NODE0: RECEIVED %d \"%s\"\n", buf->type, buf->text);
nn_freemsg (buf);
}
return 1;
}
// push.cpp
#include <iostream>
#include <assert.h>
#include <stdio.h>
#include <nanomsg/ipc.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef WIN32 || WIN64
#include <windows.h>
#include <time.h>
#include <thread>
#else
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>
#include <nanomsg/pubsub.h>
#include <nanomsg/pipeline.h>
const char *url = "ipc:///tmp/pipeline.ipc";
typedef struct{
int type;
char text[1024];
}buf_t;
int main ()
{
buf_t *buf = NULL;
buf = (buf_t *)malloc(sizeof(buf_t));
buf->type = 1;
memset(buf->text,0,1024);
memcpy(buf->text,"hello,world !",strlen("hello,world !"));
int sz_msg = sizeof(buf_t);
int sock = nn_socket (AF_SP, NN_PUSH);
assert (sock >= 0);
assert (nn_connect (sock, url) >= 0);
printf ("NODE1: SENDING %d \"%s\"\n", buf->type,buf->text);
int bytes = nn_send (sock, buf, sz_msg, 0);
assert (bytes == sz_msg);
return nn_shutdown (sock, 0);
}