美文网首页
UDP Client

UDP Client

作者: 招风小妖怪 | 来源:发表于2019-07-15 15:41 被阅读0次
    import java.net.*;
    class Client
    {
        Client()
        {
            try
            {
                //服务器IP地址
                InetAddress    ip     = InetAddress.getByName("127.0.0.1");
                //代表具体应用程序
                int            port   = 9000;
                //i开辟空间,用来形成数据包
                byte           buf[]  = new byte[200];
                //备用数据包,等着接收对方传递过来的数据
                DatagramPacket rDP    = new DatagramPacket(buf,200);
                //接收和发送引擎
                DatagramSocket socket = new DatagramSocket();
                
                for(int i=0;i<10;i++)
                {
                    Thread.sleep(1000);
                    String info = "问世间****为何物";
                    //把我们的字符串形成packet
                    DatagramPacket sendPacket=StringToPacket(ip,port,info);
                    //发送
                    socket.send(sendPacket);
                    //接收
                    socket.receive(rDP);
                    //把接收到的数据转换为字符串
                    String str = PacketToString(rDP);
                    System.out.println("from Server:"+str);
                }
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        
        public static void main(String s[])
        {
            Client client = new Client();
        }
        
        //把字符串转换为数据包
        DatagramPacket StringToPacket(InetAddress ip,int port,String message)
        {
            //String ----->byte[] + ip  +port  = DatagramPacket
            //查看字符串有多大
            int    length = message.length();
            //根据大小开辟空间
            byte   buf[]  = new byte[length];
            //把字符串的内容导入数据包
            buf           = message.getBytes();
            //把byte[]+ip+port------->数据包
            DatagramPacket  dp = new DatagramPacket(buf,0,buf.length,ip,port);
            return dp; 
        }
        
        //DatagramPacket----->byte[]-------->String
        //把数据包转换为字符串
        String PacketToString(DatagramPacket dp)
        {
            //查看数据包大小
            int  length = dp.getLength();
            //根据大小开辟空间
            byte buf[]  = new byte[length];
            //把数据包的内容转入字符数组中
            buf         = dp.getData();
            //把字符数组的内容转换为字符串
            String str  = new String(buf,0,length);
            return str;
        }
    }
    

    相关文章

      网友评论

          本文标题:UDP Client

          本文链接:https://www.haomeiwen.com/subject/nybnkctx.html