发送端
public class TalkSend implements Runnable {
private DatagramSocket client ;
private BufferedReader reader;
private String toIP ;
private int toPort ;
public TalkSend(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() {
while(true) {
String data;
try {
data = reader.readLine();
byte[] datas = data.getBytes();
//3、 封装成DatagramPacket 包裹,需要指定目的地
DatagramPacket packet =new DatagramPacket(datas,0,datas.length,
new InetSocketAddress(this.toIP,this.toPort));
//4、发送包裹send(DatagramPacket p)
client.send(packet);
if(data.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 5、释放资源
client.close();
}
}
接收端
public class TalkReceive implements Runnable {
private DatagramSocket server ;
private String from ;
public TalkReceive(int port,String from) {
this.from = from ;
try {
server=new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true) {
// 2、准备容器 封装成DatagramPacket 包裹
byte[] container =new byte[1024*60];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
// 3、阻塞式接收包裹receive(DatagramPacket p)
try {
server.receive(packet);//阻塞式
// 4、分析数据
byte[] datas =packet.getData();
int len = packet.getLength();
String data=new String(datas,0,len);
System.out.println(from+":"+data);
if(data.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 5、释放资源
server.close();
}
}
测试:
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkSend(7777,"localhost",9999)).start(); //发送
new Thread(new TalkReceive(8888,"老师")).start(); //接收
}
}
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkReceive(9999,"学生")).start(); //接收
new Thread(new TalkSend(5555,"localhost",8888)).start(); //发送
}
}
关注公众号,可以免费获取毕业设计项目、各种免费软件、资料,笔记哦。
|