我有如下代码:
Bytebuffer buffer1= ByteBuffer.allocate(1024); Bytebuffer buffer2= ByteBuffer.allocate(1024);
而(真){
selector.select();
System.out.println("Ready Selector: "+num);
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator it = selectedKeys.iterator();
while(it.hasNext())
{
SelectionKey key= (SelectionKey) it.next();
if(key.isReadable())
{
if(key.attachment.toString("Socket1")
{
//read data and store in buffer 1
SocketChannel channel1= (SocketChannel) key.channel();
while (true) {
int number_of_bytes=channel1.read(buffer1);
if (number_of_bytes <= 0) {
System.out.println("Number of bytes: "+number_of_bytes);
if(number_of_bytes==-1)
{
key.cancel();
channel1.close();
}
break;
}
}
else if(key.attachment.toString("Socket2")
{
//read data and store in buffer 2
SocketChannel channel2= (SocketChannel) key.channel();
while (true) {
int number_of_bytes=channel1.read(buffer2);
if (number_of_bytes <= 0) {
System.out.println("Number of bytes: "+number_of_bytes);
if(number_of_bytes==-1)
{
key.cancel();
channel2.close();
}
break;
}
}
}
}
现在我面临的问题是,我只从一个套接字获取数据。就像我首先打开 socket1 并输入了一些数据一样。我可以在上面的代码中读取该数据,但未读取 socket2 数据。同样,如果我先运行 socket2 然后再运行 socket1,我可以读取 socket2 数据但无法读取 socke1 数据。请帮我找出代码中的错误..