Abhishek Nayak
Abhishek Nayak

Reputation: 3748

Send files as message in JeroMQ

In JeroMQ how to send files with content type of file and other properties with single message.

in client:

build file message and send to server

DataInputStream inStrm = file.getContent();
ZMsg msg = ZMsg.load(inStrm);
msg.send(sender);

Is there any way to set properties to the message? like:

msg.setProperties("Content-Type", "application/xml");
msg.setProperties("fileName", "abc.pdf");

and in server, receive file:

Poller items = new ZMQ.Poller (2);
items.register(receiver, ZMQ.Poller.POLLIN);
while (true) {
    try{
        items.poll();       
        if (items.pollin(0)) {
            ZMsg msg = ZMsg.recvMsg(receiver);
            //save file to disk
        }
    }catch(Exception e){
        LOG.error("Error while receive file: ", e);
    }
}

Upvotes: 1

Views: 1047

Answers (1)

DontPanic
DontPanic

Reputation: 1367

There is another way. ZeroMq has Multipart-Messages

It is very useful in my opinion. In jeromq/jzmq libs you can use it in this way:

Store a data from file in byte array. Make a multipart ZMsg, put all headers and data you need inside:

ZMsg outMsg = new ZMsg();
outMsg.add(new ZFrame("application/xml"));
outMsg.add(new ZFrame("abc.pdf"));
outMsg.add(new ZFrame(bytes)); // here is the data from file
outMsg.send(outSocket);

Receive ZMsg from another socket and get all data from it:

ZMsg inMsg = ZMsg.recvMsg(inSocket);
String contentType = inMsg.pop().toString();
String fileName = inMsg.pop().toString();
byte[] fileData = inMsg.pop().getData();

Or you can do it in any other convenient way, by serializing all necessary headers in one byte array and using only two frames, etc.

Upvotes: 3

Related Questions