import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Set;
先创建一个服务器端用来存储对话和ip地址信息。用map保证ip不能重复。
public class Server extends Thread {
long l = 2000;
// 定义一个Stringbuffer
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DatagramSocket ds;
HashMap<String, InetAddress> al;
static StringBuilder sb = new StringBuilder();
public Server(DatagramSocket ds,HashMap<String, InetAddress> al) {
this.ds = ds;
this.al = al;
}
@Override
public synchronized void run() {
Set<String> ks = al.keySet();
for (String k : ks) {
// 创建一个需要发送的数据包
DatagramPacket ndp = new DatagramPacket(sb.toString().getBytes(),
sb.toString().getBytes().length, al.get(k), ds.getPort());
try {
//向所有用户发送改动的数据包
ds.send(ndp);// Thread.sleep(l);
// l += 1000;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
//创建一个服务器端口。
DatagramSocket ds = new DatagramSocket(8888);HashMap<String, InetAddress> al = new LinkedHashMap<String, InetAddress>();
while (true) {
byte[] b = new byte[102400];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
String msg = new String(b);
System.out.println(msg.trim());
InetAddress address = dp.getAddress();
al.put(dp.getAddress().getHostAddress(), dp.getAddress());
// 推送数据给所有ip但不包括自己
sb = new StringBuilder();
sb.append(dp.getAddress().getHostAddress()).append(":")
.append(msg.trim()).append("\t")
.append(sdf.format(new Date())).append("\n");
Server s = new Server(ds,al);
//启动多线程
s.start();}
}
}
//发送端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client extends Thread {
DatagramSocket ds;
public Client(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
while (true) {
byte b[] = new byte[102400];
DatagramPacket dp = new DatagramPacket(b, b.length);
try {
ds.receive(dp);
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(new String(b).trim());
}
}
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(9999);
Client c = new Client(ds);
c.start();
while (true) {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String msg = br.readLine();
DatagramPacket ndp = new DatagramPacket(msg.getBytes(),
msg.getBytes().length,
InetAddress.getByName("192.168.1.43"), 8888);
ds.send(ndp);
}
}
}