在JeroMQ中,如何使用单个消息发送具有文件内容类型和其他属性的文件。

在客户中:

建立文件消息并发送到服务器

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


有什么方法可以设置消息的属性?喜欢:

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


在服务器中,接收文件:

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);
    }
}

最佳答案

还有另一种方法。 ZeroMq具有Multipart-Messages

我认为这非常有用。
在jeromq / jzmq库中,您可以通过以下方式使用它:

将文件中的数据存储在字节数组中。
制作一个多部分的ZMsg,将所需的所有标头和数据放入其中:

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);


从另一个套接字接收ZMsg并从中获取所有数据:

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


或者,您可以通过将所有必要的标头序列化为一个字节数组并仅使用两个帧等方式,以任何其他便捷的方式进行操作。

10-07 14:25
查看更多