*多线程互相发送与接收
封装两个线程
发送端
package com.TaskUDP;
import javax.print.attribute.standard.NumberUp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TaskSender implements Runnable {
DatagramSocket datagramSocket = null;
BufferedReader reader =null;
private int formPort;
private String toIP;
private int toPort;
public TaskSender(int formPort, String toIP, int toPort) {
this.formPort = formPort;
this.toIP = toIP;
this.toPort = toPort;
try {
datagramSocket = new DatagramSocket(formPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
String date=reader.readLine();
byte[] dates=date.getBytes();
DatagramPacket packet = new DatagramPacket(dates, 0, dates.length,new InetSocketAddress(this.toIP,this.toPort));
datagramSocket.send(packet);
if (date.equals("bye")){
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
datagramSocket.close();
}
}
接收端
package com.TaskUDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class TaskReceive implements Runnable{
DatagramSocket datagramSocket =null;
private int port;
private String msgForm;
public TaskReceive(int port,String msgForm) {
this.port = port;
this.msgForm=msgForm;
try {
datagramSocket = new DatagramSocket(port);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
byte[] container = new byte[2048];
DatagramPacket datagramPacket = new DatagramPacket(container,0,container.length);
datagramSocket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
String receiveDate = new String(data, 0, data.length);
System.out.println(msgForm+":"+receiveDate);
if (receiveDate.equals("bye")){
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
datagramSocket.close();
}
}
实现
package com.TaskUDP;
public class TaskStudent {
public static void main(String[] args) {
Thread sender = new Thread(new TaskSender(7777,"localhost",9999));
Thread Recevie = new Thread(new TaskReceive(8888,"老师"));
sender.start();
Recevie.start();
}
}
package com.TaskUDP;
public class TaskTaecher {
public static void main(String[] args) {
Thread sender = new Thread(new TaskSender(5555,"localhost",8888));
Thread Recevie = new Thread(new TaskReceive(9999,"学生"));
sender.start();
Recevie.start();
}
}
|