简体   繁体   中英

How to close a DatagramSocket when it is in receive state

In my Android application I send out UDP packets and I use this code to wait for a particular one. When it arrives, I don't need to listen anymore. However, it is in "receive mode", and when I call socket.close() , it throws an exception. Somehow I should stop it.

How can I stop receiving without an exception?

socket.send(packet);
Log.d(Tags.DEBUG, "Sent");    
while (shouldRunning)
{
  byte[] buf = new byte[1024];
  DatagramPacket packet2 = new DatagramPacket(buf, buf.length);
  Log.d(Tags.DEBUG, "Receive start");
  //if (socket != null && !socket.isClosed())
  {
    socket.receive(packet2);
    Log.d(Tags.DEBUG, "ADDR" + packet2.getAddress().toString());
    String data = String.valueOf(packet2.getData());
    Log.w(Tags.DEBUG, "Data: " + data);
    if (data.equals(Tags.SPEC1))
      shouldRunning= false;
  }
  //else
    //shouldRunning= false;
}

And I close the socket this way:

@Override
protected void onCancelled()
{ 
  if (socket != null)
  {
    //socket.disconnect();
    shouldRunning=false;
    socket.close();
    socket = null;
  }
}

And I get this exception:

java.net.SocketException: Socket closed
at org.apache.harmony.luni.platform.OSNetworkSystem.recv(Native Method) at dalvik.system.BlockGuard$WrappedNetworkSystem.recv(BlockGuard.java:321) at org.apache.harmony.luni.net.PlainDatagramSocketImpl.doRecv(PlainDatagramSocketImpl.java:172) at org.apache.harmony.luni.net.PlainDatagramSocketImpl.receive(PlainDatagramSocketImpl.java:181) at java.net.DatagramSocket.receive(DatagramSocket.java:402)
at com.example.Data.DataAsyncTask.Networking(DataAsyncTask.java:745)

You should put a timeout on the socket:

socket.setSoTimeout(1000);

On SocketTimeoutException continue the while loop. When done shouldRunning==true close the socket after the while loop terminates.

OnCancelled() should only set the flag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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