一:引言
实现一方 到另一方可以发送信息,而另一方也能回复信息。这里用到了多线程,开辟两条不同的执行路径,一个执行接收信息,一个执行发送信息,但其端口号 要对应 ,即一个发送端口,对应一个接收端口。
二:上码:
1:发送端类的实现
package com.wyj.three;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;/*** 发送端* * @author 86155**/
public class Demo12_talk发送02 implements Runnable{private DatagramSocket client;private BufferedReader reader;private int port;private int toport;private String toIP;public Demo12_talk发送02(int port,int toport,String toIP) {this.port = port;this.toport = toport;this.toIP = toIP;try {client = new DatagramSocket(port);reader = new BufferedReader(new InputStreamReader(System.in));} catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void run() {// TODO Auto-generated method stubwhile( true ) {String msg ;try {msg = reader.readLine();byte[] dates = msg.getBytes();// 3.封装成 DatagramPacket 包裹 指定目的地 即Ip地址和端口DatagramPacket packet = new DatagramPacket(dates, 0,dates.length, new InetSocketAddress(this.toIP,this.toport));// 4.发送包裹 send(DatagramPacket p)client.send(packet);if(msg.equals("bye")) {break;}}catch( IOException e ) {e.printStackTrace();}}client.close();}}
2:接受端类的实现
package com.wyj.three;import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;/*** 接收端* * * @author 86155**/
public class Demo11_talk接收端02 implements Runnable{DatagramSocket server;public Demo11_talk接收端02(int port) {try {server = new DatagramSocket(port);} catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true) {byte [] container = new byte[1024*60];DatagramPacket packet = new DatagramPacket(container,container.length);
// 3.阻塞式接受包裹 receive(DatagramPacket p)try {server.receive(packet);//会有延迟byte[] dates = packet.getData();int len = packet.getLength();//得用packet的实际大小 String date = new String(dates,0,len);System.out.println(date);if( date.equals("bye")) {break;}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//释放资源server.close();}}
3:具体的实现(老师与学生的交流)
package com.wyj.three;
/*** 实现相互交流吧* * * @author 86155**/
public class Demo1_student {public static void main(String[] args) { new Thread(new Demo11_talk接收端02(9998)).start();//接受new Thread(new Demo12_talk发送02(5555, 9997, "localhost")).start();//发送}
}
4:具体的实现(老师与学生的交流)
package com.wyj.three;
/*** * 实现相互交流* * @author 86155**/
public class Demo2_teacher {public static void main(String[] args) {new Thread(new Demo12_talk发送02(8888, 9998, "localhost")).start();//发送new Thread(new Demo11_talk接收端02(9997)).start();//接受}
}