好记性不如铅笔头

java, 编程

《Java编程思想》读书笔记:UDP

最近用到了UDP实现一个小功能,就找了下UDP的实现代码,这里备份下简单的实现。

备注:

UDP的业务很简单,知道了对方的IP和端口号,无需建立连接,就可以发送数据。

public class UDPTools
{
 public static final UDPTools Instance = new UDPTools();
 private UDPTools()
 {}
 
 public static interface onRevUDPDataController
 {
  public void onRevUDPData(byte [] data, int offset, int length);
 }
 
 private int localSvrPort = 60000;
 private int remotePort = 50000;
 
 private DatagramSocket client = null;
 private DatagramSocket server = null;
 private onRevUDPDataController controller;
 private String remoteIP;
 private volatile boolean isReading = true;
 
 public boolean deinit()
 {
  if (client != null)
  {
   client.close();
  }
  
  if (server != null)
  {
   server.close();
  }
  client = null;
  server = null;
  return true;
 }
 
 public boolean init(onRevUDPDataController controller, int localSvrPort, int remotePort, String remoteIP)
 {
  if (client != null)
  {
   return false;
  }
  
  if (null == controller 
    || localSvrPort < 1024 || remotePort < 1024 || localSvrPort > 65535 || remotePort > 65535
    || null == remoteIP || remoteIP.length() > "192.168.168.168".length())
  {
   return false;
  }
  this.controller = controller;
  this.localSvrPort = localSvrPort;
  this.remotePort = remotePort;
  this.remoteIP = new String(remoteIP);
  
  try
  {
   client = new DatagramSocket();
   server = new DatagramSocket(this.localSvrPort);
   isReading = true;
  }
  catch (SocketException e)
  {
   e.printStackTrace();
   if (client != null)
   {
    client.close();
   }
   
   if (server != null)
   {
    server.close();
   }
   client = null;
   server = null;
   
   return false;
  }
  return true;
 }
 
 
 
 public boolean sendToSvr(byte[] data, int offset, int length)
 {
  if (client != null)
  {
   DatagramPacket pack;
   try
   {
    pack = new DatagramPacket(data, offset, length,InetAddress.getByName(remoteIP), remotePort);
    client.send(pack);
   }
   catch (UnknownHostException e)
   {
    e.printStackTrace();
   }
   catch (IOException e)
   {
    e.printStackTrace();
   }
  }
  else
  {
   return false;
  }
  return true;
 }
 
 public boolean stopReadFromRemote()
 {
  isReading = false;
  return true;
 }
 public boolean beginReadFromRemote()
 {
  try
  {
   while (isReading)
   {
    byte[] message = new byte[1024];
    DatagramPacket packet = new DatagramPacket(message, message.length);
    server.receive(packet);
    controller.onRevUDPData(packet.getData(), packet.getOffset(), packet.getLength());
   }
   return true;
  }
  catch (IOException e)
  {
   e.printStackTrace();
//   controller.onRevUDPData(null, 0, 0);
   return false;
  }
 }
}

 

发表评论

17 + 9 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据