UDP多线程在线咨询
发送端:
public class TalkSend implements Runnable{DatagramSocket socket = null;BufferedReader br = null;private int fromPort;private String toIP;private int toPort;public TalkSend(int fromPort,String toIP,int toPort){this.fromPort = fromPort;this.toIP = toIP;this.toPort = toPort;try {socket = new DatagramSocket();br = new BufferedReader(new InputStreamReader(System.in));} catch (SocketException e) {throw new RuntimeException(e);}}@Overridepublic void run() {while (true){String s = null;try {s = br.readLine();byte[] datas = s.getBytes();DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));socket.send(packet);if (s.equals("bye")){break;}} catch (IOException e) {throw new RuntimeException(e);}}socket.close();}
}接受端:
public class TalkReceive implements Runnable{DatagramSocket socket = null;private int port;private String mygFrom;public TalkReceive(int port,String mygFrom){this.port = port;this.mygFrom = mygFrom;try {socket = new DatagramSocket(port);} catch (SocketException e) {throw new RuntimeException(e);}}@Overridepublic void run() {while (true){try {byte[] container = new byte[1024];DatagramPacket packet = new DatagramPacket(container, 0, container.length);socket.receive(packet);byte[] data = packet.getData();String receiveData = new String(data, 0, packet.getLength());System.out.println(mygFrom+":"+receiveData);if (receiveData.equals("bye")){break;}} catch (IOException e) {throw new RuntimeException(e);}}socket.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 TalkSend(5555,"localhost",8888)).start();new Thread(new TalkReceive(9999,"学生")).start();}
}