服务器端
public class UDPServer { public static void main(String[]args) throws Exception{ byte[] buf = new byte[100]; DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); DatagramSocket datagramSocket = new DatagramSocket(9995); while(true){ datagramSocket.receive(datagramPacket); System.out.println("data is :" + new String(datagramPacket.getData())); } } }
?
客户端
public class UDPClient { public static void main(String[] args) throws Exception { byte[] buf = new String("UDP TEST data from client").getBytes(); ; DatagramPacket datagramPacket = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),9995); DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.send(datagramPacket); } }
?