发送端
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TalkSend implements Runnable {
private DatagramSocket client;
private BufferedReader br;
private InetSocketAddress address;
public TalkSend(int port, InetSocketAddress address) {
try {
this.client = new DatagramSocket(port);
br = new BufferedReader(new InputStreamReader(System.in));
this.address = address;
} catch (SocketException e) {
}
}
@Override
public void run() {
while (true) {
try {
String str = br.readLine();
byte[] data = str.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(data, 0, data.length, this.address);
client.send(datagramPacket);
if (str.equals("bye")) {
break;
}
} catch (Exception e) {
}
}
client.close();
System.out.println("end");
}
}
接收端
package com;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* 接收端:使用面向对象封装
*/
public class TalkReceive implements Runnable {
private DatagramSocket server;
public TalkReceive(int port) {
try {
this.server = new DatagramSocket(port);
} catch (SocketException e) {
}
}
@Override
public void run() {
while (true) {
try {
byte[] container = new byte[1024 * 60];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
server.receive(packet);
byte[] data = packet.getData();
int len = packet.getLength();
String s = new String(data, 0, len);
System.out.println(s);
if (s.equals("bye")) {
break;
}
} catch (Exception e) {
}
}
server.close();
System.out.println("end");
}
}
package com;
import java.net.InetSocketAddress;
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkReceive(5555)).start();
new Thread(new TalkSend(1111, new InetSocketAddress("127.0.0.1", 2222))).start();
}
}
package com;
import java.net.InetSocketAddress;
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkReceive(2222)).start();
new Thread(new TalkSend(3333, new InetSocketAddress("127.0.0.1", 5555))).start();
}
}