我有这个代码,但它不能在2台不同的计算机上工作,我改变了我的防火墙,但它不起作用。
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.rmi.RMISecurityManager;
import java.util.ArrayList;
import java.util.HashMap;
public class TestingDota{
private static String name;
public static void main(String args[]){
name = args[0];
final InetAddress group;
final String address = "230.0.0.1";
final int port = 9876;
try{
group = InetAddress.getByName(address);
}catch(Exception e){
e.printStackTrace();
return;
}
HashMap<String, Tupla> map = new HashMap<String,Tupla>();
try{
final MulticastSocket socket = new MulticastSocket(port);
socket.setReuseAddress(true);
socket.joinGroup(group);
socket.setTimeToLive(2);
new Thread(){
public void run(){
while(true){
String msg = ManagementFactory.getRuntimeMXBean().getName()+ "," + name;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(), group, port);
try {
socket.send(packet);
Thread.sleep(1000);
} catch (IOException e){
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
while(true){
byte[] buf = new byte[512];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String msg = new String(packet.getData()).trim();
int index = msg.indexOf(',');
String key = msg.substring(0,index);
String name = msg.substring(index+1, msg.length());
long time = System.currentTimeMillis();
if(map.containsKey(key)){
Tupla t = map.get(key);
t.time = time;
}else{
Tupla t = new Tupla();
t.name = name;
t.time = time;
map.put(key, t);
mostrar(map);
}
int size = map.size();
ArrayList<String> list = new ArrayList<String>();
for(String k : map.keySet()){
Tupla t = map.get(k);
if(time - t.time> 1500 ){
list.add(k);
}
}
for(String x : list) map.remove(x);
if(size > map.size()){
mostrar(map);
}
Thread.sleep(100);
}
}catch(Exception e){
e.printStackTrace();
}
}
private static void mostrar(HashMap<String, Tupla> map) {
for(String k : map.keySet()){
Tupla t = map.get(k);
System.out.println(t.name);
}
System.out.println();
}
static class Tupla{
String name;
long time;
}
}
要运行此程序,请写:$ java TestingDota someName,它适用于同一台计算机中的多个终端,但它不能在不同的计算机上工作