首页 > 代码库 > java UDP通信

java UDP通信

服务器端:

public class UDPServer{
 public static void main(String[] args) throws Exception{
  byte buf[] = new byte[1024];
  DatagramPacket dp = new DatagramPacket(buf,buf.length);
  DatagramSocket ds = new DatagramSocket(5678);
  while(true){
   ds.receive(dp);
   System.out.println(new String(buf,0,dp.getLength()));
  }
  
 }
}

 

客户端:

import java.net.*; import java.io.*;

public class UDPClient{  

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

    byte[] buf = (new String("Hello Server!")).getBytes();   

    DatagramPacket dp = new DatagramPacket(buf,buf.length,    new InetSocketAddress("127.0.0.1",5678));

      DatagramSocket ds = new DatagramSocket(4567);   

    ds.send(dp);   

    ds.close();  

  }

}

java UDP通信