我在桌面PC上制作了一个简单的client-server
应用程序并成功运行它,同时在同一台PC上创建客户端和服务器。
然后我交叉编译应用程序在树莓上运行它。当我在覆盆子上运行这个应用程序时,覆盆子上的客户端和服务器,它工作得很好。我可以看到发送和接收的消息。
现在我将PC作为服务器和覆盆子作为客户端,但我看不到收到的消息。这是我的代码。
PC端代码:
zctx_t *ctx = zctx_new ();
void *reader = zsocket_new (ctx, ZMQ_PULL);
int rc = zsocket_connect (reader, "tcp://PC-IP:5555");
printf("wait for a message...\n");
while(1)
{
char *message = zstr_recv (reader);
Sleep(10);
printf("Message: %s",message);
}
zctx_destroy (&ctx);
Raspberry Side Code:
zctx_t *ctx = zctx_new ();
void *writer = zsocket_new (ctx, ZMQ_PUSH);
int rc = zsocket_bind (writer, "tcp://PC-IP:5555");
while(1)
{
cout<<"sending................."<<endl;
zstr_send (writer, "HELLO");
}
zsocket_destroy (ctx, writer);
我怎样才能让它发挥作用?
答案 0 :(得分:1)
服务器应始终绑定到其自己的接口(所有IPv4接口的本地IP地址或0.0.0.0
或IPv4和IPv6的0::0
)。
客户端应始终连接到远程IP地址。
由于您希望您的PC成为服务器从Raspberry Pi 客户端中提取消息,我认为您应该使用以下内容:
PC端代码
zctx_t *ctx = zctx_new ();
void *reader = zsocket_new (ctx, ZMQ_PULL);
int rc = zsocket_bind (reader, "tcp://PC-IP:5555");
printf("wait for a message...\n");
while(1)
{
char *message = zstr_recv (reader);
Sleep(10);
printf("Message: %s",message);
}
zctx_destroy (&ctx);
Raspberry Side Code
zctx_t *ctx = zctx_new ();
void *writer = zsocket_new (ctx, ZMQ_PUSH);
int rc = zsocket_connect (writer, "tcp://PC-IP:5555");
while(1)
{
cout<<"sending................."<<endl;
zstr_send (writer, "HELLO");
}
zsocket_destroy (ctx, writer);
当然,您也可以将Raspberry Pi作为推送服务器运行,将PC端作为拉客户端运行。在这种情况下,您可以使用:
...
int rc = zsocket_connect (reader, "tcp://raspberrypi-ip:5555");
...
和
...
int rc = zsocket_bind (writer, "tcp://raspberrypi-ip:5555");
...