我在0mq上使用protobuf-c使客户端和服务器代码相互通信

下面是客户鳕鱼的片段


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。

最佳答案

zmq_send和zmq_recv似乎处理zmq_msg_t结构,而不只是缓冲区。
也许您应该尝试创建这样的结构,而不仅仅是发送缓冲区?
请参见http://api.zeromq.org/2-1:zmq-sendhttp://api.zeromq.org/2-1:zmq-recv中的示例

关于c - 通过zeromq发送protobuf-c数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22118233/

10-11 23:18
查看更多