0
votes

I'm trying to use a zeromq socket as a raw TCP client socket in C++. I have a TCP server in a different program which I would like to send data to. When I connect my Zeromq client to the server, I am able to receive data from the server but unable to send data to the TCP server. When sending I get the following error: Unhandled error, zmq::error_t Have any idea how to make it work?

zmq::context_t *ctx = new zmq::context(100, 100);
void *raw_socket = new zmq::socket_t(*ctx, ZMQ_STREAM);
zmq::socket_t *socket = static_cast<zmq::socket_t*>(raw_socket);

socket->connect("tcp://127.0.0.1:5555");

char message[] = "HELLO, WORLD!"
socket->send(message, strlen(message), ZMQ_SNDMORE)
1
What is the need for raw_socket? - Fureeish
The TCP server which I connect to is a TCP server built using python, so I can't use the ZMTP protocol to connect to it. - J. Doe
But in the example it's completely useless - Fureeish
What do you meen? - J. Doe
You assign a pointer to zmq::socket_t to a void*. Then, the only thing you do with it is to cast it back to zmq::socket_t*. That is completely useless. You would achieve the same (plus save some memory) by simply doing zmq::socket_t *socket = new zmq::socket_t(*ctx, ZMQ_STREAM);. I see no point in having a raw_socket at all. - Fureeish

1 Answers

0
votes

When you send or receive anything on a ZMQ_STREAM type socket the first data frame should be an identifier that indicates where the subsequent frames should go or where they came from.

When using the ZMQ_STREAM socket as a server (i.e you call bind on the socket) then you can just extract this identity frame with recv and resend it when you respond.

When used as a client (i.e you call connect on the socket) then you need to obtain the identity from the socket, you can do this via getsockopt with the ZMQ_IDENTITY flag.

The identity size is limited to a maximum of 255 bytes.

// get the id after you've called connect
std::size_t id_size = 256;
char id[ 256 ];
socket->getsockopt( ZMQ_IDENTITY, &id, &id_size );

// send the id frame
socket->send(id, id_size, ZMQ_SNDMORE);

// then your data
char message[] = "HELLO, WORLD!";
socket->send(message, strlen(message), ZMQ_SNDMORE);

The documentation on ZMQ_STREAM goes into more detail about how you'll be notified and control connections, disconnections etc.