发送端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//UDP通信中的发送端
public class send {
public static void main(String[] args) throws IOException {
//定义一个发送端Socket
DatagramSocket ds=new DatagramSocket();
//从键盘输入数据
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line=br.readLine())!=null){
if("886".equals(line)){
break;
}
//定义一个数据包
byte[]by=line.getBytes();
DatagramPacket dp=new DatagramPacket(by,by.length, InetAddress.getByName("192.168.12.1"),10010);
int len=dp.getLength();
ds.send(dp);
}
}
}
接收端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//定义一个UDP接受端
public class receive {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket(10010);
while (true) {
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by, by.length);
ds.receive(dp);
//解析数据包
int len = dp.getLength();
String s = new String(dp.getData(), 0, len);
System.out.println("接受到的数据是:" + s);
}
}
}
发送端
接收端:
输入886结束通信