2

在 Android 上使用 localsockets。我有一个用户从另一个连接读取。连接被告知通过关闭套接字、关闭输入流和中断它的线程来停止读取。它不会停止尝试读取,直到另一端关闭。那么,有没有办法让它中断阅读?

这是我的问题的一个非常简化的示例。当您尝试使用频道时,问题变得更加严重。它将(分别)阻止线程/通道上的中断/关闭请求。

你应该得到这个日志:

V/test    ( 4416): bound
V/test    ( 4416): accepted
V/test    ( 4416): stop
V/test    ( 4416): stop exit
V/test    ( 4416): closing
V/test    ( 4416): done reading?
V/test    ( 4416): all closed

第一类:

public class Runner1 implements Runnable
{

public static Runner1       me  = null;

public InputStream          in;
public ReadableByteChannel  rb;
LocalSocket                 ls;
public Thread               thisThread;

public Runner1() {
    me = this;
}

@Override
public void run()
{
    thisThread = Thread.currentThread();
    try
    {
        LocalServerSocket lss = new LocalServerSocket(Test2Activity.location);
        ls = lss.accept();
        Log.v("test", "accepted");

        in = ls.getInputStream();
        byte[] buffer = new byte[10];
        in.read(buffer);
        // rb = Channels.newChannel(in);

        // ByteBuffer bb = ByteBuffer.allocate(100);
        // rb.read(bb);
        Log.v("test", "done reading?");
        ls.close();
        lss.close();
        Log.v("test", "all closed");
    }
    catch (IOException e)
    {
        Log.v("test", "error1");
        e.printStackTrace();
    }
}

public static void stop()
{
    Log.v("test", "stop");
    try
    {
        // me.rb.close();
        me.in.close();
        me.ls.close();
        // me.ls.shutdownInput();
        // me.ls.shutdownOutput();
    }
    catch (IOException e)
    {
        Log.v("test", "error - stop" + e.toString());
        e.printStackTrace();
    }

    me.thisThread.interrupt();

    Log.v("test", "stop exit");
}
}

类2:

public class Runner2 implements Runnable
{
@Override
public void run()
{

    try
    {
        sleep(1500);
        LocalSocket ls = new LocalSocket();
        ls.connect(new LocalSocketAddress(Test2Activity.location));
        Log.v("test", "bound");
        WritableByteChannel wc = Channels.newChannel(ls.getOutputStream());
        sleep(3000);
        Runner1.stop();
        sleep(4000);
        Log.v("test", "closing");
        ls.close();
    }
    catch (IOException e)
    {
        Log.v("test", "error" + e.toString());
        e.printStackTrace();
    }
}

public void sleep(int time)
{
    try
    {
        Thread.sleep(time);
    }
    catch (InterruptedException e1)
    {
    }
}
}
4

2 回答 2

0

只需关闭套接字以进行输入。这会将 EOS 传递给 read()。然后读取线程应该关闭套接字本身并退出,这应该已经编码。

于 2013-10-14T23:36:46.773 回答
0

我能找到解决此问题的最佳方法是设置超时并检查套接字是否在另一个线程中关闭。

可悲的是,当您设置超时时,您不会收到 TimeoutException :(

于 2013-10-14T21:21:54.997 回答