package study_04;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkServer implements Runnable{
public static void main(String[] args) {
new Thread(new TalkServer(9999)).start();//接收端
new Thread(new TalkClient(1111, "localhost", 2222)).start();//发送端
}
private DatagramSocket server;
public TalkServer(int port) {
try {
server = new DatagramSocket(port);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
byte[] container = new byte[1024 *50];
DatagramPacket packet = new DatagramPacket(container, 0,container.length);
try {
server.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] datas = packet.getData();
String msg = new String(datas,0,datas.length);
System.out.println(msg);
if (msg.equals("bye")) {
break;
}
}
server.close();
}
}
package study_04;
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 TalkClient implements Runnable{
public static void main(String[] args) {
new Thread(new TalkClient(8888, "localhost", 9999)).start();
new Thread(new TalkServer(2222)).start();
}
private DatagramSocket client;
private BufferedReader reader;
private String toIp;
private int toPort;
public TalkClient(int port,String toIp,int toPort) {
this.toIp = toIp;
this.toPort = toPort;
try {
client = new DatagramSocket(port);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
String data;
try {
data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0,data.length(),new InetSocketAddress(this.toIp,this.toPort));
client.send(packet);
if (data.equals("bye")) {
break;
}
} catch (Exception e) {
// TODO: handle exception
}
}
client.close();
}
}