简单的UDP程序
接受端:
package com.dcz.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Receive { public static void main(String[] args) throws IOException { DatagramSocket receive = new DatagramSocket(17002); byte[] buf = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buf, 1024); receive.receive(datagramPacket); String str = new String(datagramPacket.getData(), 0 , datagramPacket.getLength()); System.out.println("接受数据:" + str); receive.close(); } }
发送端:
package com.dcz.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Send { public static void main(String[] args) throws IOException { String data = "带发送的数据!"; DatagramSocket send = new DatagramSocket(17006); DatagramPacket datagramPacket = new DatagramPacket( data.getBytes(), data.getBytes().length, InetAddress.getLocalHost(), 17002); send.send(datagramPacket); send.close(); } }