我正在开发一个谷歌玻璃的应用程序,需要监听的工作线程的UDP数据包(与现有的系统发送UDP数据包整合)。我previously发布了一个问题(见here)并获得其提供了关于如何做到这一点一些指导答案。使用中的其他讨论的方法,我将有被屏蔽的DatagramSocket.receive()辅助线程。
I'm developing a Google Glass app which needs to listen for UDP packets in a worker thread (integrating with an existing system which sends UDP packets). I previously posted a question (see here) and received an answer which provided some guidance on how to do this. Using the approach in the other discussion I'll have a worker thread which is blocked on DatagramSocket.receive().
进一步阅读建议,我认为我需要能够启动/停止这种需求。因此,这使我想到我张贴在这里的问题。如何可以以这样的方式,以能够中断(正常)UDP监听执行上述操作?有一些方法可以让我很好要求插座从另一个线程打出来的接收()调用的?
Further reading suggests to me that I'll need to be able to start/stop this on demand. So this brings me to the question I'm posting here. How can I do the above in such a way as to be able to interrupt (gracefully) the UDP listening? Is there some way I can "nicely" ask the socket to break out of the receive() call from another thread?
或者是有另一种方式在中断的方式监听UDP数据包,这样我就可以开始/停止监听线程需要应对设备事件?
Or is there another way to listen for UDP packets in an interruptable fashion so I can start/stop the listener thread as needed in response to device events?
推荐答案
我的建议:
private DatagramSocket mSocket;
@Override
public void run() {
Exception ex = null;
try {
// read while not interrupted
while (!interrupted()) {
....
mSocket.receive(...); // excepts when interrupted
}
} catch (Exception e) {
if (interrupted())
// the user did it
else
ex = e;
} finally {
// always release
release();
// rethrow the exception if we need to
if (ex != null)
throw ex;
}
}
public void release() {
// causes exception if in middle of rcv
if (mSocket != null) {
mSocket.close();
mSocket = null;
}
}
@Override
public void interrupt() {
super.interrupt();
release();
}
轮廓清晰,简单,经常发布和中断停止你干净2例。
clean cut, simple, always releases and interrupting stops you cleanly in 2 cases.
相关推荐
最新文章