我试图在多个套接字通道上等待读取数据。我已经从网上复制了示例代码,但是对我来说不起作用。问题是“选择”调用正确阻塞,直到接收到第一个数据,但此后立即返回0(未就绪)。我的代码(用于单个通道)如下。
final String HOST = "<REDACTED>.com";
final int PORT = 2000;
SocketChannel MyChannel;
Selector MySelector;
void doSelect()
{
SelectionKey key;
int nready;
long nr;
try {
ByteBuffer bytebuf = ByteBuffer.allocate( 1024 ); // allocate bytebuffer
InetSocketAddress addr = new InetSocketAddress( HOST, PORT); // form addr
MyChannel = SocketChannel.open(); // create socketchan
MyChannel.connect( addr ); // connect to data src
while( !MyChannel.finishConnect() ) Thread.sleep( 1000 ); // wait til connected
MyChannel.configureBlocking( false ); // set non-blocking
MySelector = Selector.open(); // open new selector
key = MyChannel.register( MySelector, SelectionKey.OP_READ ); // register for reads
while( true ) { // loop forever
nready = MySelector.select(); // block til something ready
if( nready <= 0 ) { // nothing ready?
logit( "not ready: select returned "+nready );
MyChannel.close();
break; // give up
}
if( key.isReadable() ) { // readable?
nr = MyChannel.read( bytebuf ); // read data
logit( "read "+nr+" bytes" );
}
} // end while
} // end try
catch( Exception e ) {
logit( "doSelect: "+e );
return;
}
}
//@ Log a message to logcat
void logit(String msg) { Log.i( "MYAPP", msg ); }
更新10/19/2019
根据@ user207421的建议,我修改了代码以遍历所选键。这没什么区别。第一次接收后,select()调用仍然没有阻塞,并且从通道读取的内容为读取的0字节。
新代码的节选(为我的可读性重命名了一些变量)
while( true ) { // loop forever
nready = selector.select(); // call select: block til something ready
if( nready <= 0 ) { // nothing ready? (should never happen)
break; // give up
}
// PROCESS ALL SELECTED KEYS
Set<SelectionKey> selected = selector.selectedKeys(); // get selected key set
Iterator<SelectionKey> iter = selected.iterator(); // create iterator
while( iter.hasNext() ) { // while has more
key = iter.next(); // get next key
if( key.isReadable() ) { // check if ready to read
nr = chan.read( bb ); // read from channel
if( nr > 0 ) { // got some data?
printByteBuffer( bb );
}
else {
// should never happen! (but it does)
}
}
else if( key.isWritable()) {} // never happens!
else if( key.isAcceptable()) {} // never happens!
else if( key.isConnectable()) {} // never happens!
iter.remove();
} // end while hasnext
} // end while
//@ Convert ByteBuffer to byte array and print
void printByteBuffer(
ByteBuffer bb ) // BB to print
{
int nrem;
byte[] bytes;
String str;
bb.flip(); // reset position
nrem = bb.remaining();
bytes = new byte[nrem]; // alloc byte array
bb.get( bytes ); // get bytes from bytebuf
str = new String( bytes ); // cnvt to string
log( "received \""+str+"\"" );
}
任何建议,不胜感激。
最佳答案
我根据评论找到了解决方案。显然,ByteBuffer是“已满”。我通过在通道read()之前发出“ .clear()”来解决此问题。
我不明白为什么这样做是有必要的,因为ByteBuffer比任何接收到的数据都要大(1000字节),但是仍然可以。
回复:阻止模式:我在网上找到的每个示例都说,应将通道设置为非阻止,以使Selector select()正常工作。无论如何,我短暂地尝试了阻止模式,但是对此并不满意。