- 1、基于udp组播
消息发送
public class UdpSender {
private final static String url = "udpm://239.255.76.68:7667?ttl=1";
public static void main(String[] args) throws IOException {
LCM lcm = new LCM(url);
int num = 0;
LcmParam param = new LcmParam();
param.id = 1;
param.name = "hello"
while (true){
lcm.publish("CHANNEL_ONE", param);
System.out.println("send msg " + ++num);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消息接收
public class UdpReceiver {
private final static String url = "udpm://239.255.76.68:7667?ttl=1";
public static void main(String[] args) {
try {
lcm.subscribe("CHANNEL_ONE", new LCMSubscriber() {
@Override
public void messageReceived(LCM lcm, String channel, LCMDataInputStream ins) {
LcmParam p;
try {
p = new LcmParam(ins);
System.out.println("receive id " + p.id);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
while(true){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
- 2、基于TCP, 需要启动一个tcp服务端
tcp服务
public class TcpServer {
public static void main(String[] args) {
try {
TCPService tcpService = new TCPService(7666);
} catch (IOException e) {
e.printStackTrace();
}
}
}
消息发送
public class TcpSender {
public static void main(String[] args) {
try {
LCM lcm = new LCM("tcpq://127.0.0.1:7666");
LcmParam param = new LcmParam();
param.id = 1;
param.name = "hello";
while (true){
lcm.publish("TCP", param);
Thread.sleep(5000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
消息接收
public class TcpReceiver {
public static void main(String[] args) {
try {
LCM lcm = new LCM("tcpq://127.0.0.1:7666");
lcm.subscribe("TCP", (lcm1, channel, ins) -> {
try {
LcmParam param = new LcmParam(ins);
System.out.println("receive " + param.name);
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 3、基于内存队列, 需要使用同一个lcm对象,在一个进程内。
public class TestMemq {
private final static String url = "memq://";
public static void main(String[] args) throws IOException {
LCM lcm = new LCM(url);
//
new Thread(() -> {
LcmParam p = new LcmParam();
p.id= 2;
p.name = "hello";
while (true) {
lcm.publish("CHANNEL_ONE", p);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
lcm.subscribe("CHANNEL_ONE", new LCMSubscriber() {
@Override
public void messageReceived(LCM lcm, String channel, LCMDataInputStream ins) {
LcmParam p;
try {
p = new LcmParam(ins);
System.out.println("receive name " + p.name);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}).start();
while (true){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- 4、基于file方式,还没有看懂,待测试
备注:
1、自带的编码解码,java端测试需要,把所有引用类型属性全部初始化,否则编码异常。
2、中文字符串,官网写的是utf-8 string,但测试传递中文为乱码,可能是我使用方式不对。
自己处理方式是,将中文转为unicode,在传递。