我在2个线程中使用一个SocketChannel,一个线程用于发送数据,另一个线程用于接收数据。Java NIO TCP超时问题
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(ip,port));
socketChannel.configureBlocking(false);
线程1:使用上述的SocketChannel写入数据
线程2:使用相同的SocketChannel读取
我不使用任何选择器与所述的SocketChannel如我所需的数据写入和读取异步(使用2个不同的线程)
问题:当连接丢失时,socketchannel.write()和socketchannel.read()操作不会引发任何错误。它只是阻止操作。
我需要检测连接丢失。
我试过在线程2中使用心跳方法,但因为读取操作刚好阻塞,所以此方法无法工作。有没有其他方法可以在不使用新线程中的心跳的情况下检测连接丢失?
如果存在连接丢失,写入/读取时是否可能抛出错误?
在此先感谢。
编辑:
主题1:
public void run() {
socketChannel = SendAndReceivePacketUtil.createConnection(ip, port);
socketChannel.configureBlocking(false);
RecTask task = new RecTask(socketChannel);
Thread recThread = new Thread(task);
recThread.start();
while(true)
{
byte[] data= getDataFromQueue(ip);
if(data!= null) {
//print(new String(data));
sendPacket(data, socketChannel);
}
}
}
线程2:(RecTask)
public void run() {
while(true) {
byte[] data = receivePacket(socketChannel);
//print(new String(data));
}
}
两个线程1 & 2具有的try-catch-finally块。最后关闭套接字通道。
了sendpacket:
int dataSent = 0;
while (dataSent < data.length) {
long n = socketChannel.write(buf);
if (n < 0) {
throw new Exception();
}
dataSent += (int) n;
}
receivePacket:
int dataRec = 0;
byte[] data = new byte[length];
ByteBuffer buffer = ByteBuffer.wrap(data);
while (dataRec < length) {
long n = socketChannel.read(buffer);
if (n < 0) {
throw new Exception();
}
dataRec += (int) n;
}
return data;
我发送和连续接收数据。但是一旦连接丢失,就不会打印,代码就会卡住。它是一个android wifi直接应用程序。对于连接丢失情况,我只需关闭wifi模块。
2015-05-01
armor--