现在的位置: 首页 > 综合 > 正文

网络编程(4)–UDP

2018年04月06日 ⁄ 综合 ⁄ 共 1805字 ⁄ 字号 评论关闭

1.使用DatagramSocket实现Server/Client结构的网络通信程序

   public class UdpServer

  {

   public static final int PORT = 30000;

   private static final int DATA_LEN = 4096;

   private DatagramSocket socket = null;

   byte[] inBuff = new byte[DATA_LEN];

   private DatagramPacket inPacket = new DatagramPacket(inBuff,inBuff.length);

   private DatagramPacket outPacket;

   String[] books = new String[];

   {"轻量级J2EE企业应用实战","基于J2EE的Ajax宝典","Struts2权威指南","ROR敏捷开发最佳实践"

    };

  public void init() throws IOException

  {

   try

   {

    socket = new DatagramSocket(PORT);

   for(int i=0;i<1000;i++)

  {

   socket.receive(inPacket);

   System.out.println(inBuff == inPacket.getData());

   System.out.println(new String(inBuff,0,inPacket.getLength()));

   byte[] sendData = books[i % 4].getBytes();

   outPacket = new DatagramPacket(sendData,sendData.length,inPacket.getSocketAddress());

   socket.send(outPacket);

  }

   }

 finally

 {

  if(socket != null)

  {

    socket.close();

  }

 }

 }

public static void main() throws IOException

 {

  new  UdpServer().init();

 }

 }

 

public class UdpClient

{

  public static final int DEST_PORT = 30000;

  public static final String DEST_IP = "127.0.0.1";

  private static final int DATA_LEN =4096;

  private DatagramSocket socket = null;

  byte[] inBuff = new byte[DATA_LEN];

  private DatagramPacket inPacket = new DatagramPacket(inBuff,inBuff.length);

  private DatagramPacket outPacket = null;

  public void init() throws IOException

 {

    try

   {

    socket = new DatagramSocket();

   //初始化发送用的DatagramSocket,它包含一个长度为0的字节数组

    outPacket = new DatagramPacket(new byte[0],0,InetAddress.getByName(DEST_IP),DEST_PORT);

   Scanner scan = new Scanner(System.in);

  while(scan.hasNextLine())

  {

    byte[] buff = scan.nextLine().getBytes();

   outPacket.setData(buff);

   socket.send(outPacket);

   socket.receive(inPacket);

  System.out.println(new String(inBuff,0,inPack.getLength()));

  }

   }

finally

{

   if(socket !=null )

   {

    socket.close();

   }

}

 }

 public static void main() throws IOException

 {

  new UdpClient().init();

}

}

抱歉!评论已关闭.