【发布时间】:2015-05-01 04:15:59
【问题描述】:
我在 2 个线程中使用一个 SocketChannel,一个线程用于发送数据,另一个用于接收数据。
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(ip,port));
socketChannel.configureBlocking(false);
线程1:使用上面的socketchannel写入数据
线程2:使用同一个socketchannel读取数据
我没有在 socketchannel 中使用任何选择器,因为我需要异步读写(使用 2 个不同的线程)
问题:当连接丢失时,socketchannel.write() 和socketchannel.read() 操作不会抛出任何错误。它只是阻止操作。
我需要检测连接丢失。
我尝试在线程 2 中使用 heartbeat 方法,但由于读取操作只是阻塞,因此该方法不起作用。有没有其他方法可以在不使用新线程中的心跳的情况下检测连接丢失?
如果连接丢失,是否可能在写入/读取时抛出错误?
提前致谢。
编辑:
线程 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 块。最后关闭socketchannel。
发送包:
int dataSent = 0;
while (dataSent < data.length) {
long n = socketChannel.write(buf);
if (n < 0) {
throw new Exception();
}
dataSent += (int) n;
}
接收包:
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 模块。
【问题讨论】:
标签: java multithreading tcp nio socketchannel