码迷,mamicode.com
首页 > 其他好文 > 详细

UDP---client+sever

时间:2015-04-03 14:51:29      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

 


public
 class UDP_Client {
       public static void main(String[] args) throws Exception {
             //1、创建服务 + 端口
            DatagramSocket client = new DatagramSocket(6666);
             //2、准备数据
            String msg = "我喜欢你" ;
             byte[] data = msg.getBytes();
             //3、打包(发送地点+端口)
            DatagramPacket packet =
                   new DatagramPacket(data, data.length , new InetSocketAddress("localhost" ,8888));
             //4、发送
            client.send(packet);
             //5、释放
            client.close();
      }
}

public class UDP_Server {
       public static void main(String[] args) throws Exception {
             //1、创建服务端+端口
            DatagramSocket server = new DatagramSocket(8888);
             //2、准备容器接收
             byte[] container = new byte[1024];
             //3、封装成包
            DatagramPacket packet = new DatagramPacket(container,container.length );
             //4、接受数据
            server.receive(packet);
             //5、分析数据
             byte[] data = packet.getData();
             int len = packet.getLength();
            System. out.println(new String(data, 0, len));
             //6、释放
            server.close();
            
      }
}

UDP---client+sever

标签:

原文地址:http://www.cnblogs.com/king-/p/4389728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!