zoukankan      html  css  js  c++  java
  • java-udp编程

    TCP/IP UDP都是基于传输层的;而udp发送数据会出现丢包的情况,发送一个数据不管对方接收不接收,发送过去就完事了;

    udp的特点:将数据源和目的封装成数据包中,不要建立连接;(DatagramPacket)

    每个数据报的大小在限制64K以内

    因无连接,是不可靠协议

    不需要建立连接,速度快;

    下面将编写一代代码展现UDP

    一、client 端

      

    public class UDPSocketClient {
        
        public static void main(String[] args) throws Throwable {
        
                //send();
            
                keySend();
        
        }
    
        private static void keySend() throws Throwable {
             
            try {
                
                //1、创建UDP服务
                DatagramSocket socket=new DatagramSocket();
                
                BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
                
                 String message=null;
                
                while((message=reader.readLine())!=null) {
                    
                    
                    if(message.equals("886"))  
                     
                        break;
                    
                    //2、 封装数据包                    
                    DatagramPacket send=new DatagramPacket(message.getBytes(),message.getBytes().length,InetAddress.getByName("localhost"), 8088);
                    //阻塞式 3、发送数据
                    socket.send(send);
                }
                //4、释放资源
                socket.close();
                
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }

    二、SERVER端

    public class UDPSocketServer {
        
        public static void main(String[] args) throws Throwable {
            //receive();
            Keyreceive();
        }
    
        private static void Keyreceive() throws Throwable {
             
            //1、创建udp socket并指定端口
            DatagramSocket socket = new DatagramSocket(8088);
            
            while(true) {
                 //2、定义数据 要接收的报文
                 byte[] bytes = new byte[1024];
                 DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
                 socket.receive(packet);//阻塞式
                 String message=new String(packet.getData(),0,packet.getData().length);
                 System.out.println("Server收到的消息为:"+message);
            }
            
             
        }
    }

    三、测试结果;

    先把server端启动,然后开启client

    客户端发送消息

    服务端接收消息

     多线程进行聊天

    一、客户端

    public class UDPSocketClientThread implements Runnable{
        
        private DatagramSocket  datagramSocket;
        public UDPSocketClientThread(DatagramSocket  datagramSocket) {
            this.datagramSocket=datagramSocket;
        }
    
        @Override
        public void run() {
            
            BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
            
             String message=null;
            
            try {
                while((message=reader.readLine())!=null) {
                    
                    if(message.equals("886"))  
                     
                        break;
                    
                    //2、发送数据
                    DatagramPacket send=new DatagramPacket(message.getBytes(),message.getBytes().length,InetAddress.getByName("192.168.43.255"), 8088);
                    //阻塞式
                    this.datagramSocket.send(send);
                }
            } catch (UnknownHostException e) {
                
                e.printStackTrace();
            } catch (IOException e) {
                
                e.printStackTrace();
            }
        }
        
    }

    二、服务端

    public class UDPSocketServerThread implements Runnable{
        
        DatagramSocket socket;
        
        public UDPSocketServerThread(DatagramSocket socket) {
            this.socket=socket;
        }
     
    
        @Override
        public void run() {
            
            while(true) {
                 //2、定义数据 要接收的报文
                 byte[] bytes = new byte[1024];
                 DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
                 try {
                    socket.receive(packet);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }//阻塞式
                 String message=new String(packet.getData(),0,packet.getData().length);
                 InetAddress inetAddress=null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                     System.out.println(inetAddress.getHostAddress()+"的消息为:"+message);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            
        }
     
    }

    三、测试运行

    public class UDPSocketRun {
        
        public static void main(String[] args) throws Throwable {
            DatagramSocket send=new DatagramSocket();
            DatagramSocket receive=new DatagramSocket(8088);
            new Thread(new UDPSocketClientThread(send)).start();
            new Thread(new  UDPSocketServerThread(receive)).start(); 
        }
    }
  • 相关阅读:
    从开发者的角度分析iOS应如何省电
    微信逆向工程之远程操作Mac
    [UIApplication sharedApplication].idleTimerDisabled=YES;不自动锁屏 [UIApplication sharedApplication].idleTimerDisabled=NO;自动锁屏
    [软件逆向]实战Mac系统下的软件分析+Mac QQ和微信的防撤回
    iOS的坑:ERRORITMS-90096: "Your binary is not optimized for iPhone 5
    iOS下简单实现滑动导航条
    遇到线程阻塞,主线程死亡的问题,线程与信号量的使用
    断点续传和分块上传
    关于Instruments-Leaks工具的归纳总结
    valueForKeyPath常用用法
  • 原文地址:https://www.cnblogs.com/hellohero55/p/11992788.html
Copyright © 2011-2022 走看看