【UDP 发送接收数据】
package com.yjf.esupplier.common.test; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * @author shusheng * @description UDP 发送接收数据 * @Email shusheng@yiji.com * @date 2019/1/6 0:21 */ public class SendDemo { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(); String str = "i love you"; // 把数据进行封装到数据报包中 DatagramPacket packet = new DatagramPacket(str.getBytes(), str.length(), InetAddress.getByName("localhost"), 6666); socket.send(packet);// 发送 byte[] buff = new byte[100]; DatagramPacket packet2 = new DatagramPacket(buff, 100); socket.receive(packet2); System.out.println(new String(buff, 0, packet2.getLength())); socket.close(); } }
package com.yjf.esupplier.common.test; import java.net.DatagramPacket; import java.net.DatagramSocket; /** * @author shusheng * @description UDP 发送接收数据 * @Email shusheng@yiji.com * @date 2019/1/7 23:24 */ public class ReceiveDemo { public static void main(String[] args) throws Exception { // 先接收数据 DatagramSocket socket = new DatagramSocket(6666); byte[] buff = new byte[100]; DatagramPacket packet = new DatagramPacket(buff, buff.length); socket.receive(packet);// 接受传来的数据包 System.out.println(new String(buff, 0, packet.getLength())); // 发送数据 String str = "me too"; DatagramPacket packet2 = new DatagramPacket(str.getBytes(), str.length(), packet.getAddress(), packet.getPort()); socket.send(packet2); socket.close(); } }
终身学习者