android nio wifi 拥堵 超时,Java NIO TCP超时问题

我在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--

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值