在JeroMQ中将文件作为消息发送

时间:2016-12-20 19:33:37

标签: java zeromq jeromq

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

在客户端:

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

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

并在服务器中,接收文件:

/order-screen/store/1/London

1 个答案:

答案 0 :(得分:3)

还有另一种方式。 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();

或者你可以通过任何其他方便的方式,通过在一个字节数组中序列化所有必需的标题并仅使用两个帧等来实现。