在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
第1课:
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)
{
}
}
}
答案 0 :(得分:0)
我能找到最好的解决方法是设置超时并检查套接字是否在另一个线程中关闭。
可悲的是,当你设置超时时,你没有得到TimeoutException :(
答案 1 :(得分:0)
只需关闭套接字即可进行输入。这将为read()提供EOS。然后读取线程应该关闭套接字本身并退出,这应该已经编码。