免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4551 | 回复: 1
打印 上一主题 下一主题

Java Socket UDP协议 的超级简单使用 [复制链接]

论坛徽章:
1
操作系统版块每日发帖之星
日期:2015-06-19 22:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-16 13:26 |只看该作者 |倒序浏览
Java socket udp协议

send.jpg

server.jpg

SocketClient.java
  1. import java.net.DatagramPacket;
  2. import java.net.DatagramSocket;
  3. import java.net.InetAddress;
  4. import java.net.UnknownHostException;

  5. /**
  6. * 消息发送端
  7. *
  8. * @author 肖蕾
  9. */
  10. public class SocketClient
  11. {
  12.     private DatagramSocket socket = null;
  13.     private DatagramPacket packet = null;
  14.     private byte[] def = new byte[1];
  15.     private InetAddress address;
  16.     private int port = -1;

  17.     public SocketClient()
  18.     {
  19.         try
  20.         {
  21.             socket = new DatagramSocket();
  22.             packet = new DatagramPacket(def, def.length);
  23.         } catch (Exception e)
  24.         {
  25.             throw new RuntimeException("SocketClient 初始化失败");
  26.         }
  27.     }

  28.     public SocketClient(String ip, int port)
  29.     {
  30.         try
  31.         {
  32.             socket = new DatagramSocket();
  33.             packet = new DatagramPacket(def, def.length);
  34.             address = InetAddress.getByName(ip);
  35.             packet.setAddress(address);
  36.             this.port = port;
  37.             packet.setPort(this.port);
  38.         } catch (UnknownHostException e)
  39.         {
  40.             throw new RuntimeException(
  41.                     "SocketClient(String ip,int port) 发送ip设置失败");
  42.         } catch (Exception e)
  43.         {
  44.             throw new RuntimeException("SocketClient 初始化失败");
  45.         }
  46.     }


  47.     /**
  48.      * 发送消息
  49.      *
  50.      * @param data
  51.      *            发送的内容
  52.      * @param ip
  53.      *            发送的ip地址
  54.      * @param port
  55.      *            发送的端口号
  56.      */
  57.     public void sendMessage(byte[] data)
  58.     {
  59.         try
  60.         {
  61.             packet.setData(data);
  62.             packet.setLength(data.length);
  63.             socket.send(packet);
  64.         } catch (Exception e)
  65.         {
  66.             String errorMsg = "";
  67.             if (address == null)
  68.             {
  69.                 errorMsg += "\n发送的地址为空 setAddress(String ip)\n";
  70.             }
  71.             if (port == -1)
  72.             {
  73.                 errorMsg += "发送的端口为空 setPort(int port)\n";
  74.             }
  75.             throw new RuntimeException(errorMsg);
  76.         }
  77.     }

  78.     /**
  79.      * 设置发送的IP地址
  80.      *
  81.      * @param ip
  82.      *            发送的ip地址
  83.      */
  84.     public void setAddress(String ip)
  85.     {
  86.         try
  87.         {
  88.             address = InetAddress.getByName(ip);
  89.             packet.setAddress(address);
  90.         } catch (UnknownHostException e)
  91.         {
  92.             throw new RuntimeException("setAddress(String ip) 发送ip设置失败");
  93.         }
  94.     }

  95.     /**
  96.      * 设置发送的端口
  97.      *
  98.      * @param port
  99.      *            发送的端口
  100.      */
  101.     public void setPort(int port)
  102.     {
  103.         this.port = port;
  104.         packet.setPort(this.port);
  105.     }

  106.     /**
  107.      * 释放资源
  108.      */
  109.     public void close()
  110.     {
  111.         if (socket != null)
  112.         {
  113.             socket.close();
  114.         }
  115.     }
  116. }
复制代码
SocketServer.java
  1. import java.net.DatagramPacket;
  2. import java.net.DatagramSocket;

  3. public class SocketServer
  4. {
  5.     private byte[] buff= null;
  6.     private DatagramPacket packet = null;
  7.     private DatagramSocket server = null;
  8.     private OnMessageListener listener = null;
  9.     private boolean loop = false;
  10.     Thread thread = new Thread()
  11.     {
  12.         public void run()
  13.         {
  14.             try
  15.             {
  16.                 while (loop)
  17.                 {
  18.                     if (server != null)
  19.                     {
  20.                         server.receive(packet);
  21.                         byte []data = packet.getData();
  22.                         byte []msg = new byte[packet.getLength()];
  23.                         for (int i = 0; i < msg.length; i++)
  24.                         {
  25.                             msg[i] = data[i];
  26.                         }
  27.                         if (SocketServer.this.listener != null)
  28.                         {
  29.                             SocketServer.this.listener.getmsg(msg,packet.getAddress().getHostAddress(),packet.getPort());
  30.                         }
  31.                     }
  32.                 }
  33.             } catch (Exception e)
  34.             {
  35.             }
  36.         };
  37.     };
  38.     /**
  39.      * 构造函数 初始化数据
  40.      * @param port      端口
  41.      * @param size      缓冲区的长度
  42.      * @throws Exception
  43.      */
  44.     public SocketServer(int port, int size)
  45.     {
  46.         try
  47.         {
  48.             buff= new byte[size];
  49.             packet = new DatagramPacket(buff, buff.length);
  50.             server = new DatagramSocket(port);
  51.         } catch (Exception e)
  52.         {
  53.             throw new RuntimeException(e);
  54.         }
  55.     }
  56.     /**
  57.      * 设置数据的获取者
  58.      * @param listener
  59.      */
  60.     public SocketServer setOnMessageListener(OnMessageListener listener)
  61.     {
  62.         this.listener = listener;
  63.         return this;
  64.     }
  65.     /**
  66.      * 开始接收数据
  67.      */
  68.     public void start()
  69.     {
  70.         loop = true;
  71.         thread.start();
  72.     }
  73.     /**
  74.      * 关闭流  释放资源
  75.      */
  76.     public void close()
  77.     {
  78.         loop = false;
  79.         if (server != null)
  80.         {
  81.             server.close();
  82.         }
  83.     }
  84.      
  85. }
  86. /**
  87. * 数据获取者
  88. * @author 肖蕾
  89. */
  90. interface OnMessageListener
  91. {
  92.     /**
  93.      * 获取发送的数据,ip地址 以及端口号
  94.      * @param data  数据
  95.      * @param ip    ip地址
  96.      * @param port  端口号
  97.      */
  98.     public void getmsg(byte []data,String ip,int port);
  99. }
复制代码

论坛徽章:
59
2015七夕节徽章
日期:2015-08-24 11:17:25ChinaUnix专家徽章
日期:2015-07-20 09:19:30每周论坛发贴之星
日期:2015-07-20 09:19:42ChinaUnix元老
日期:2015-07-20 11:04:38荣誉版主
日期:2015-07-20 11:05:19巳蛇
日期:2015-07-20 11:05:26CU十二周年纪念徽章
日期:2015-07-20 11:05:27IT运维版块每日发帖之星
日期:2015-07-20 11:05:34操作系统版块每日发帖之星
日期:2015-07-20 11:05:36程序设计版块每日发帖之星
日期:2015-07-20 11:05:40数据库技术版块每日发帖之星
日期:2015-07-20 11:05:432015年辞旧岁徽章
日期:2015-07-20 11:05:44
2 [报告]
发表于 2015-08-12 13:06 |只看该作者
UDP比TCP简单。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP