客户端
public class Useer {
public static void main(String[] args) throws SocketException {
DatagramSocket user = new DatagramSocket(101);
// 发送数据
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
String line = br.readLine();
if ("bye".equals(line)) {
break;
}
byte[] b = line.getBytes();
DatagramPacket page = new DatagramPacket(b, b.length, InetAddress.getLocalHost(), 100);
user.send(page);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
// 接收数据
new Thread(new Runnable() {
@Override
public void run() {
byte[] b = new byte[1024];
while (true) {
DatagramPacket page = new DatagramPacket(b, b.length);
try {
user.receive(page);
System.out.println("客户端:" + page.getAddress().getHostAddress() + " " + page.getPort() + " "
+ new String (page.getData()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
服务端:
public class Server {
public static void main(String[] args) throws SocketException {
DatagramSocket cline = new DatagramSocket(100);
//发送数据
new Thread(new Runnable() {
@Override
public void run() {
try {
//从控制台接收字符串
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
//每次读一行
String line = br.readLine();
if ("bye".equals(line)) {
break;
}
//将字符串转换为byte数组
byte[] b = line.getBytes();
// 数据包(传输4个参数)
DatagramPacket page = new DatagramPacket(b, b.length, InetAddress.getLocalHost(), 101);
cline.send(page);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
//接收数据
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
// 2.创建接受数据的数据包
byte[] b = new byte[1024];
// 数据包(接收定义长度)
DatagramPacket page = new DatagramPacket(b, b.length);
// cline接收page里的数据
cline.receive(page);
System.out.println("服务器:" + page.getAddress().getHostAddress() + " " + page.getPort() + " "
+ new String(page.getData()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}