import java.io.IOException;
import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.net.UnknownHostException;import org.junit.Test;
//关于UDP的编程实现,UDP(不可靠的传输,但是是最快的方式)public class TestUdp { @Test public void send() { DatagramSocket ds = null; try { ds = new DatagramSocket(); byte[] b = "我是要发送的数据".getBytes(); //创建一个数据报,每个数据不能大于64k,每一个都记录数据信息,发送端的IP,端口号以及发送到接收端的IP和端口号 DatagramPacket pack = new DatagramPacket(b, 0, b.length,InetAddress.getByName("127.0.0.1"),8989); ds.send(pack); ds.close(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(ds != null){ ds.close(); } } }@Test
public void accept(){ DatagramSocket ds=null; try { ds = new DatagramSocket(8989); byte[] b = new byte[1024]; DatagramPacket pack = new DatagramPacket(b, 0, b.length); ds.receive(pack); String str = new String (pack.getData(), 0, pack.getLength()); System.out.println(str); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(ds != null){ ds.close(); } }}
}