- 仅供初学者浏览,自娱自乐代码。如有不足,还请指出。
package groupChat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class ServerTest {
static Map<InetAddress,Integer> map=new HashMap<InetAddress,Integer>();
public static void main(String[] args) throws SocketException, UnknownHostException {
DatagramSocket ds=new DatagramSocket(9999);
while(true){
byte [] b=new byte[1024];
DatagramPacket dp=new DatagramPacket(b, b.length);
try {
ds.receive(dp);
} catch (IOException e) {
e.printStackTrace();
}
InetAddress add=dp.getAddress();
if(check(add,dp.getPort())){
map.put(add, dp.getPort());
}
String message="ip:"+add.getHostAddress()+":"+dp.getPort()+"="+new String(dp.getData(),0,dp.getLength());
System.out.println(message);
new Thread(new SendTest(map,message)).start();
}
}
public static boolean check(InetAddress add,int port){
for(Entry<InetAddress, Integer> en:map.entrySet()){
if(en.getKey().getHostAddress().equals(add.getHostAddress())&&en.getValue().equals(port)){
return false;
}
}
return true;
}
}
package groupChat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Map;
import java.util.Map.Entry;
public class SendTest implements Runnable{
Map<InetAddress,Integer> map;
String message;
public SendTest(Map<InetAddress,Integer> map,String message){
this.map=map;
this.message=message;
}
@Override
public void run() {
try {
DatagramSocket ds=new DatagramSocket();
byte[]b=message.getBytes();
for(Entry<InetAddress, Integer> en:map.entrySet()){
DatagramPacket dp=new DatagramPacket(b, b.length,en.getKey(),en.getValue());
ds.send(dp);
}
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}