【问题标题】:Need an interruptable way to listen for UDP packets in a worker thread需要一种可中断的方式来侦听工作线程中的 UDP 数据包
【发布时间】:2014-03-10 19:54:41
【问题描述】:

我正在开发一个需要在工作线程中侦听 UDP 数据包的 Google Glass 应用程序(与发送 UDP 数据包的现有系统集成)。我之前发布了一个问题(请参阅here)并收到了一个答案,该答案提供了一些有关如何执行此操作的指导。使用其他讨论中的方法,我将有一个工作线程,它在 DatagramSocket.receive() 上被阻塞。

进一步阅读向我表明,我需要能够按需启动/停止此操作。所以这让我想到了我在这里发布的问题。如何以能够(优雅地)中断 UDP 侦听的方式执行上述操作?有什么方法可以“很好地”让套接字脱离另一个线程的 receive() 调用吗?

或者是否有另一种方法以可中断的方式侦听 UDP 数据包,以便我可以根据需要启动/停止侦听器线程以响应设备事件?

【问题讨论】:

标签: java android google-glass


【解决方案1】:

我的建议:

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();
}

干净利落,简单,总是释放和打断在两种情况下完全停止。

【讨论】:

    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2014-08-22
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2013-06-12
    相关资源
    最近更新 更多