package com.yjf.esupplier.common.test; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * @author shusheng * @description UDP 发送接收数据 * @Email [email protected] * @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"; //Encapsulating the data packet to the data packets of DatagramPacket Packet = new new of DatagramPacket (str.getBytes (), str.length (), InetAddress.getByName ( "localhost"), 6666 ); socket.send (Packet); // send byte [] = BUFF new new byte [100 ]; of DatagramPacket packet2 = new new of DatagramPacket (BUFF, 100 ); Socket.Receive (packet2); System.out.println ( new 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 [email protected] * @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(); } }