1

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

1 回答 1

3

还有另一种方法。ZeroMq 具有多部分消息

在我看来这非常有用。在 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();

或者您可以通过任何其他方便的方式来完成,通过在一个字节数组中序列化所有必要的标头并仅使用两个帧等。

于 2016-12-21T16:53:26.647 回答