最简单的UDP程序,一个负责发送消息,一个接收消息。
发送类:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class SendDemo { public static void main(String[] args) throws IOException { while (true) { System.out.print("Please input data:"); byte[] say = new Scanner(System.in).nextLine().getBytes(); DatagramSocket ds = new DatagramSocket(); DatagramPacket dp = new DatagramPacket(say, say.length, InetAddress.getByName("127.0.0.1"), 1357); ds.send(dp); } } }
接收类:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class ReceiveDemo { public static void main(String[] args) throws IOException { DatagramSocket ds = new DatagramSocket(1357); while (true) { byte[] buf = new byte[2048]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); System.out.println("from:" + dp.getAddress().getHostName() + " message:" + new String(dp.getData(), 0, dp.getData().length)); } } }