UDP通信程序
UDP通信原理
UDP协议是一种不可靠的网络协议,它在通信两端各自建立一个Socket对象,但是这两个Socket只是发送,接收数据对象,因此对于基于UDP协议的通信双方而言,没有所谓的客户端和服务器的概念
Java 提供了DatagramSocket类作为基于UDP协议的Socket
UDP发送程序
- 创建发送端的Socket对象(DatagramSocket)
- 创建数据,并把数据打包
- 调用DatagramSocket对象的方法发送数据
- 关闭发送端
public class SendDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket();
//数据报包
byte[] byts="Hello World!".getBytes();
int length=byts.length;
InetAddress address=InetAddress.getByName("127.0.0.1");
int port=10086;
DatagramPacket dp=new DatagramPacket(byts,length,address,port);
ds.send(dp);
ds.close();
}
}
UDP接受数据
- 创建接收端的Socket对象(DatagramSocket)
- 创建数据包接收数据
- 调用DatagramSocket对象方法接收数据
- 解析数据包并把数据在控制台显示
- 关闭接收端
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket(10086);
byte[] byts=new byte[1024];
DatagramPacket dp=new DatagramPacket(byts,byts.length);
ds.receive(dp);
byte[] datas=dp.getData();
String dataString=new String(datas,0,dp.getLength());
System.out.println(dataString);
ds.close();
}
}
UDP联系
public class SendDemo {
public static void main(String[] args) throws IOException {
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[] bys=line.getBytes();
DatagramPacket dp=new DatagramPacket(bys,bys.length,
InetAddress.getByName("127.0.0.1"),10086);
ds.send(dp);
}
ds.close();
}
}
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket(10086);
byte[] bys=new byte[1024];
DatagramPacket dp=new DatagramPacket(bys,bys.length);
while (true){
ds.receive(dp);
byte[] datas=dp.getData();
String dataString=new String(datas,0,dp.getLength());
System.out.println(dataString);
}
}
}