基于UDP的Socket编程

 

public class UDPTest1

{

    public static void main(String[] args) throws Exception

    {

    //接收数据报

       DatagramSocket socket = new DatagramSocket(7000);

      

       byte[] buffer = new byte[1000];

      

       DatagramPacket packet = new DatagramPacket(buffer,1000);

      

       socket.receive(packet);

      

       System.out.println(new String(buffer, 0 , packet.getLength()));

      

      

       //发送数据报

       String str = "Welcome";

      

       DatagramPacket packet2 = new DatagramPacket(str.getBytes(),str.length(),packet.getAddress(),packet.getPort());

      

       socket.send(packet2);

      

       socket.close();

    }

}

 

 

public class UDPTest2

{

    public static void main(String[] args) throws Exception

    {

    //发送数据报

       DatagramSocket socket = new DatagramSocket();

 

       String str = "Hello World";

 

       DatagramPacket packet = new DatagramPacket(str.getBytes(),

              str.length(), InetAddress.getByName("localhost"), 7000);

      

       socket.send(packet);

      

       //接收数据报

       byte[] buffer = new byte[1000];

      

       DatagramPacket packet2 = new DatagramPacket(buffer,1000);

      

       socket.receive(packet2);

      

       System.out.println(new String(buffer,0,packet2.getLength()));

      

       socket.close();

    }

}

 

你可能感兴趣的:(socket编程)