package com.test; import org.junit.Test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class TestUDP { @Test public void client() { DatagramSocket ds = null; try { ds = new DatagramSocket(); String data = "hellow udpserver"; DatagramPacket dp = new DatagramPacket(data.getBytes(), data.length(), InetAddress.getLocalHost(), 666 ); ds.send(dp); byte[] buf = new byte[1024]; DatagramPacket dpIn = new DatagramPacket(buf, buf.length); ds.receive(dpIn); System.out.println(new String(dpIn.getData(), 0, dpIn.getLength())); ds.close(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (ds != null) { ds.close(); } } } @Test public void server() { DatagramSocket ds = null; try { ds = new DatagramSocket(666); byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); byte[] data = dp.getData(); int length = dp.getLength(); InetAddress ipClient = dp.getAddress(); int port = dp.getPort(); String str = new String(data, 0, length); System.out.println("Server received:" + str); String dataout = "hellow udpClient, i have received"; DatagramPacket dpout = new DatagramPacket(dataout.getBytes(), dataout.length(), ipClient, port); ds.send(dpout); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (ds != null) { ds.close(); } } } }