如何解决使用 JZMQ 和 PUB-SUB 套接字,为什么此测试代码无法接收我的消息?
这是一个对我来说失败的更复杂的单元测试的简化版本。它在 subSocket.recv(ZMQ.DONTWAIT)
行失败,收到 null
。如果我不设置 ZMQ.DONTWAIT
,它就会永远挂起,消息似乎永远丢失了。
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Test;
import org.zeromq.ZMQ;
public class AppTest {
@Test
public void testZmqPubSub() {
final String testSocketAddr = "ipc:///tmp/foo_bar";
final String message = "Hello,World!";
ZMQ.Context zmqContext = ZMQ.context(1);
ZMQ.Socket subSocket = zmqContext.socket(ZMQ.SUB);
Assert.assertNotNull(subSocket);
try {
subSocket.bind(testSocketAddr);
} catch (org.zeromq.ZMQException e) {
Assert.fail(e.toString());
}
subSocket.subscribe(new byte[0]); // Subscribe to everything.
ZMQ.Socket pubSocket = zmqContext.socket(ZMQ.PUB);
Assert.assertNotNull(pubSocket);
try {
pubSocket.connect(testSocketAddr);
} catch (org.zeromq.ZMQException e) {
Assert.fail(e.toString());
}
try {
Thread.sleep(1000); // ms
} catch (InterruptedException e) {}
pubSocket.send(message.getBytes(StandardCharsets.UTF_8),0);
try {
Thread.sleep(1000); // ms
} catch (InterruptedException e) {}
byte[] received = subSocket.recv(ZMQ.DONTWAIT);
if (null == received) {
Assert.fail("subSocket.recv(ZMQ.DONTWAIT) returned null");
}
Assert.assertEquals(message,new String(received,StandardCharsets.UTF_8));
}
}
这适用于 PUSH-PULL 套接字对。
在 tcp
、inproc
和 ipc
上使用 PUB-SUB 失败。
您可以使用以下存储库重现此错误:https://github.com/HalCanary/jt
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。