Commit 5cf89f14 authored by Vincent Charpentier's avatar Vincent Charpentier
Browse files

feat: implemented a working ZMQ publisher in Java.

parent b0c5ae8d
......@@ -16,6 +16,15 @@
<version>0.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
......
import netscape.javascript.JSObject;
import org.zeromq.SocketType;
import org.zeromq.ZMQ;
import org.zeromq.ZContext;
import zmqpubsub.ZmqPublisher;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.concurrent.TimeUnit;
public class Main
{
public static void main(String[] args) throws Exception
{
try (ZContext context = new ZContext())
{
ZMQ.Socket socket = context.createSocket(SocketType.PUB);
socket.bind("tcp://*:5555");
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}";
JsonObject jsonObject = (JsonObject) JsonParser.parseString(jsonString);
System.out.println(jsonObject);
while (!Thread.currentThread().isInterrupted())
{
System.out.println("waiting for message");
byte[] reply = socket.recv(0);
// Print the message
System.out.println("Received: [" + new String(reply, ZMQ.CHARSET) + "]"
);
}
ZmqPublisher publisher = new ZmqPublisher("127.0.0.1", "2001");
for(int i=0; i<10; i++)
{
publisher.publish("allData", jsonObject);
System.out.println("published");
TimeUnit.SECONDS.sleep(1);
}
......
package zmqpubsub;
import com.google.gson.JsonObject;
import netscape.javascript.JSObject;
import org.zeromq.SocketType;
import org.zeromq.ZMQ;
import org.zeromq.ZContext;
public class ZmqPublisher
{
public ZContext context;
public ZMQ.Socket socket;
public String bind;
public ZmqPublisher(String ip, String port) throws Exception
{
context = new ZContext();
socket = context.createSocket(SocketType.PUB);
bind = "tcp://"+ ip + ":" + port;
start();
}
public void start()
{
socket.bind(bind);
}
public void publish(String topic, JsonObject payload)
{
System.out.println(payload);
socket.send(topic+":"+payload);
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment