Skip to content

Instantly share code, notes, and snippets.

@shs96c
Last active January 29, 2019 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shs96c/7607f5ce1cd436418e5c5aaa54cf4ec1 to your computer and use it in GitHub Desktop.
Save shs96c/7607f5ce1cd436418e5c5aaa54cf4ec1 to your computer and use it in GitHub Desktop.
package com.example;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
public class Sockets {
@Test
public void differentContexts() throws InterruptedException {
String connection = "tcp://*:1234";
ZContext one = new ZContext();
// Create a publishing socket, and bind to the port
ZMQ.Socket bindingPublisher = one.createSocket(ZMQ.PUB);
bindingPublisher.setImmediate(true);
assertTrue(bindingPublisher.bind(connection));
// Simulate connecting from a different process, by creating
// a new context.
ZContext two = new ZContext();
// Add a subscriber
ZMQ.Socket sub = two.createSocket(ZMQ.SUB);
sub.setImmediate(true);
assertTrue(sub.connect(connection));
sub.subscribe(ZMQ.SUBSCRIPTION_ALL);
// From the new process, also try and publish events
ZMQ.Socket pub = two.createSocket(ZMQ.PUB);
pub.setImmediate(true);
assertTrue(pub.connect(connection));
// Give everything a chance to start in entirely the wrong way
Thread.sleep(1000);
assertTrue(pub.send("Hello, World!"));
String str = sub.recvStr();
System.out.println(str);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment