Java网络编程UDP通信原理 (2)

代码如下(发送端):

import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class SendMessage { public static void main(String[] args) throws Exception { // 创建发送端Socket对象 DatagramSocket sendSocket = new DatagramSocket(); // 准备需要发送的数据 String message = "hello"; // 创建一个缓冲区 byte[] messageByte = message.getBytes(); // 获取缓冲区中数据的真实长度 int messageLen = message.length(); // InetAddress实例化获取本机通信地址 InetAddress address = InetAddress.getLocalHost(); // 设置通信端口号 int port = 12345; // 打包数据 DatagramPacket sendPacket = new DatagramPacket(messageByte, messageLen, address, port); // 发送数据 sendSocket.send(sendPacket); // 发送端等待接收端成功接收信息后返回的回应 // 创建一个缓冲区,容量尽量设置大一点因为不知道发送过来的信息有多大 byte[] recevieByte = new byte[1024*10]; int len = recevieByte.length; // 接收数据报 DatagramPacket receivePacket = new DatagramPacket(recevieByte, len); // 接收数据 sendSocket.receive(receivePacket); // 获取接收端发送过来的真实长度以及数据 byte[] data = receivePacket.getData(); int length = receivePacket.getLength(); String receiveData = new String(data,0,length); // 获取发送者的IP address = receivePacket.getAddress(); String ip = address.getHostAddress(); System.out.println("接收来自:"+ip+"的数据,内容是:"+receiveData); // 关闭资源 sendSocket.close(); } }

代码如下(接收端):

import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class RecevieMessage { public static void main(String[] args) throws Exception { // 接收消息的端口(与发送端保持一致) int port = 12345; DatagramSocket recevieSocket = new DatagramSocket(port); // 设置缓冲区接收发过来的信息 byte[] receiveByte = new byte[1024*10]; int len = receiveByte.length; // 接收数据报 DatagramPacket receviePacket = new DatagramPacket(receiveByte, len); // 接收数据 recevieSocket.receive(receviePacket); // 获取实际接收到的数据及其大小 byte[] data = receviePacket.getData(); int length = receviePacket.getLength(); String receiveData = new String(data,0,length); // 获取发送者的IP InetAddress address = receviePacket.getAddress(); String ip = address.getHostAddress(); System.out.println("接收来自:"+ip+"的数据,内容是:"+receiveData); // 接收端接收到信息后发送一条确认接收的消息到发送端 String message = "OK"; byte[] messageByte = message.getBytes(); int messageLength = message.length(); // 从已收到的数据报中获取IP和port address = receviePacket.getAddress(); int port1 = receviePacket.getPort(); //构造新数据报 DatagramPacket sendPacket = new DatagramPacket(messageByte, messageLength, address, port1); // 发送数据 recevieSocket.send(sendPacket); // 关闭资源 recevieSocket.close(); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzdwds.html