Android udpserver不断接收数据信息问题

通过udpserver循环接收客户端发来的数据,将所有的数据显示在界面我这边就通过while循环在线程中接收数据,然后通过handler将数据显示在主界面上!可是为什么有时候会卡死!
   public class UDPServer implements Runnable {

        private byte[] msg = new byte[1024];

        private boolean life = true;
        private DatagramSocket dSocket = null;

        public UDPServer() {
            try {
                dSocket = new DatagramSocket(17009);
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }

        /**
         * @return the life
         */
        public boolean isServer() {
            return life;
        }

        /**
         * @param lifes the life to set
         */
        public void setServer(boolean lifes) {
            this.life = lifes;
            LogUtil.e("dSocket.isClosed()show==");
            if (life == false && dSocket != null) {
                              if (!dSocket.isClosed()) {
                    dSocket.close();
                }
                dSocket.disconnect();
              //                dSocket = null;
            }
        }

        @Override
        public void run() {
            DatagramPacket dPacket = new DatagramPacket(msg, msg.length);
                     while (life) {
                try {
                    Thread.sleep(5);
                    if (dSocket != null) {
  dSocket.receive(dPacket);
                                    String datas = ByteUtil.byte2HexStr(dPacket.getData(), dPacket.getLength());
                                            //将收到的消息发给主界面
                                              if (dPacket.getAddress() != null) {
                            Message message = new Message();
                            message.obj = dPacket.getAddress() + "--" + datas;
                            message.what = 2;
                            myHandler.sendMessage(message);
                        }
                    } else {
                        life = false;
                    }
                } catch (IOException e) {
                    life = false;
                    if (dSocket != null) {
                        if (!dSocket.isClosed()) {
                            dSocket.close();
                        }
                        dSocket.disconnect();
                    }
                } catch (InterruptedException e) {
                    life = false;
                    if (dSocket != null) {
                        if (!dSocket.isClosed()) {
                            dSocket.close();
                        }
                        dSocket.disconnect();
                    }
                }
            }
        }
    }

慕雪9649571
浏览 1121回答 0
0回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android