Udp Send(发送端)与Receive(接收端) 基本原理

来源:互联网 发布:java调用成员方法 编辑:程序博客网 时间:2024/06/10 19:41
package com.mth.udp;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;/* *UdpSend *需求:通过udp传输方式 将一段文字数据发送出去 *步骤: *1.建立udpsocket服务 *2.提供数据 并将数据封装到数据包中 *3.通过socket服务发送功能将数据包发送出去   *4.关闭资源 * */public class UdpSend {public static void main(String[] args) throws Exception {// 1。创建socket服务 通过DatagramSocket对象DatagramSocket ds = new DatagramSocket(8888);//指定用8888端口发送// 2.确定数据,并封装成数据包 通过DatagramPacket对象String str = "你好 ";byte[] buf = str.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10000);// 3.通过socket服务 将已有的数据包发送出去 通过send()方法ds.send(dp);// 4.关闭资源ds.close();}}
package com.mth.udp;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;/* *UdpReceive *需求:定义一个应用程序 用于接收Udp协议传输的数据并处理的 * 步骤: * 1.定义udpsocket服务 通常会监听一个端口  确实就是给这个接收网络应用程序定义数字标识 * 方便与明确哪些数据过来该应用数据可以处理。 * 2.定义一个数据包 因为要存储接收到的自己数据 * 因为数据包对象中有更多功能可以提取自己数据中的不同数据信息; * 3.通过sockt服务receive()方法存入已定义的数据包中 * 4.通过数据包对象的特有功能 将这些不同的数据取出 打印在控制台上 * 5.关闭资源 *  * */public class UdpReceive {public static void main(String[] args) throws Exception {// 1.创建udp socket服务,建立端点DatagramSocket ds = new DatagramSocket(10000);while (true) {// 2.定义数据包byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);// 3.通过服务的receive方法将接收到的数据存入到数据包中ds.receive(dp);// 阻塞式方法// 4.通过数据包的方法获得数据包中的数据String ip = dp.getAddress().getHostAddress();// 获取到有效的数据String data = new String(dp.getData(), 0, dp.getLength());int port = dp.getPort();System.out.println(ip + "..." + data + "...." + port);}// 5 关闭资源// ds.close();}}


0 0