通过zeromq发送protobuf-c数据

时间:2014-03-01 18:09:11

标签: c protocol-buffers zeromq

我使用protobuf-c over 0mq

让客户端和服务器代码相互通信

下面是客户端鳕鱼剪了

void *context = zmq_ctx_new ();
void *requester = zmq_socket (context, ZMQ_REQ);
char collector[100]; 

char buffer[MAX_MSG];

sprintf(collector,"tcp://%s:%s",argv[2],argv[3]);
zmq_connect (requester, collector);

LogMsg proto_msg = LOG_MSG__INIT;
void *buf;      // Buffer to store serialized data
unsigned len;   // Length of serialized data  
proto_msg.name=argv[1];//assigning arg1 the node name
proto_msg.ip="127.0.0.1"; //TODO get IP im connected to
proto_msg.pid=getpid();
proto_msg.has_pid = 1;

//sending Hello to Collector to register 
proto_msg.level = "HELLO";
len = log_msg__get_packed_size (&proto_msg);
buf = malloc (len);         
log_msg__pack (&proto_msg, buf);  
printf("Writing %d serialized bytes to socket: Handshaking with Collector\n",len); // See the length of message
zmq_send(requester, buf,len, 0);
在服务器端

我有以下代码

#include "generator.h"

int main (void)
{
    //  Socket to talk to clients
void *context = zmq_ctx_new ();
void *responder = zmq_socket (context, ZMQ_REP);
int rc = zmq_bind (responder, "tcp://*:5555");
uint8_t buffer[MAX_MSG];
int i=0;
assert (rc == 0);
zmq_recv (responder, buffer, MAX_MSG, 0);
printf ("recieved -> %s\n",buffer);
LogMsg *ptr_msg; 
ptr_msg = log_msg__unpack(NULL,i,buffer); // Deserialize the serialized input
if (ptr_msg == NULL)
{ // Something failed
    fprintf(stderr,"error unpacking incoming message\n");
    return 1;
}

log_msg__free_unpacked(ptr_msg,NULL);
    return 0;
}

但是当服务器收到消息时,它会发出以下错误

recieved -> 
B1  127.0.0.1??"HELLO/?? 
message 'Log_msg': missing required field 'name'

供参考.proto文件如下

message Log_msg
{
required string name=1; //Node Name
optional string IP=2 [default = "127.0.0.1"]; //Node IP Addr
optional int32 PID=3 [default = 9999]; //Process ID
optional string level=4 [default = "INFO"]; //Log Info Level
optional int64 datim=5; //UNIX Time Stamp
optional string msg=6; //Log message

}

我假设当我在线上传输它时它会被破坏。任何想法如何我可以正确发送它。在线示例为c ++显示了这一点。我需要C.

1 个答案:

答案 0 :(得分:1)

zmq_send和zmq_recv似乎处理zmq_msg_t结构而不仅仅是缓冲区。

也许你应该尝试创建这样的结构,而不仅仅是发送你的缓冲区?

请参阅http://api.zeromq.org/2-1:zmq-sendhttp://api.zeromq.org/2-1:zmq-recv

中的示例