1)发送端
package com.sxt.udp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class TalkClient implements Runnable{
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) {
e.printStackTrace();
}
}
@Override
public void run() {
String msg;
while(true){
try {
msg= reader.readLine();
byte[] data=msg.getBytes();
DatagramPacket dp = new DatagramPacket(data, 0, data.length, new InetSocketAddress(this.toIP, this.toPort));
client.send(dp);
if(msg.equals("bye")) break;
} catch (IOException e) {
e.printStackTrace();
}
}
client.close();
}
}
2)接收端
package com.sxt.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkServer implements Runnable{
private DatagramSocket server;
public TalkServer(int port) {
try {
server= new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
byte[] container = new byte[1024 * 60];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
try {
server.receive(packet);
byte[] datas = packet.getData();
int len = packet.getLength();
String msg=new String(datas,0,datas.length);
System.out.println(msg);
if(msg.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
server.close();
}
}
3)学生端(可接收与发送)
package com.sxt.udp;
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkClient(8888,"localhost",6666)).start();
new Thread(new TalkServer(7777)).start();
}
}
4)老师端(可接收与发送)
package com.sxt.udp;
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkServer(6666)).start();
new Thread(new TalkClient(5555,"localhost",7777)).start();
}
}