简体   繁体   English

一段时间后如何关闭UDP接收套接字?

[英]How to close UDP receiving socket after a period of time?

I new a thread like this 我这样新建一个线程

        new Thread(new Runnable() {
        @Override
        public void run() {
            DatagramSocket udpSocket = null;

            try {
                udpSocket = new DatagramSocket(null);
                udpSocket.setReuseAddress(true);
                udpSocket.setBroadcast(true);
                udpSocket.bind(new InetSocketAddress(BIND_PORT));


                InetAddress ipAddress = InetAddress.getByName(BROADCAST);
                DatagramPacket udpSendPacket = new DatagramPacket(sendMessage, sendMessage.length, ipAddress, SEND_PORT);

                // udp send
                udpSocket.send(udpSendPacket);


                // udp receive
                byte[] receiveMessage = new byte[100];
                DatagramPacket udpReceivePacket = new DatagramPacket(receiveMessage, receiveMessage.length);

                long startTime = System.currentTimeMillis();
                while ((System.currentTimeMillis()-startTime) < 5000) {
                    udpSocket.receive(udpReceivePacket);
                    Log.v(TAG, new String(receiveMessage, 0, udpReceivePacket.getLength()));

                }
                udpSocket.close();
                Log.v(TAG, "udp: close");
            } catch (Exception e) {
                Log.e(TAG, e.toString());
                e.printStackTrace();
            } finally {
                if (udpSocket != null) {
                    udpSocket.close();
                    Log.v(TAG, "udp: close");
                }
            }
        }
    }).start();

I want to receive a list of returned message, but seems this try never go to the finally and this socket never close. 我想收到返回消息的列表,但似乎此尝试永远不会执行到finally,并且此套接字永远不会关闭。 It may cause some problem at the next time I want to bind this port. 下次我要绑定此端口时,可能会引起一些问题。 How can I make sure this port close after a period of time. 一段时间后如何确保该端口关闭。

If you want your call to DatagramSocket.receive to finish at your time limit, you will need to make a call to DatagramSocket.setSoTimeout(int) , which sets a timeout on the read operation. 如果希望对DatagramSocket.receive的调用在您的时间限制内完成,则需要对DatagramSocket.setSoTimeout(int)进行调用,这将设置读取操作的超时。

Your while loop would look something like this: 您的while循环如下所示:

long startMillis = System.currentTimeMillis();
long endMillis = startMillis + 100;
long currentMillis;
try {
  while ((currentMillis = System.currentTimeMillis()) < endMillis) {
    long soTimeout = endMillis - currentMillis;
    udpSocket.setSoTimeout((int) soTimeout);
    updSocket.receive(udpReceivePacket);
    // ...
  }
} catch (SocketTimeoutException e) {
  // This means that the socket timed out without receiving data in time.
  // You can still read from the socket again (although you probably
  // want to increase the timeout again).
}

Note that System.currentTimeMillis() is not actually intended for measuring elapsed time, though - it is the wall time. 请注意,尽管System.currentTimeMillis()实际上不是用于测量经过时间的-它是墙时间。 You should maybe use System.nanoTime() instead, which is intended for that purpose (obviously you'll need to divide the times by 1e6). 您可能应该改用System.nanoTime()来实现此目的(显然,您需要将时间除以1e6)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM