对于java的NIO我不是很了解,正在学习中,以下是一个例子,可以读取telnet的输入
package com.test.nio;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;
public class TestSelector {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Selector selector=SelectorProvider.provider().openSelector();
ServerSocketChannel ssc= ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.socket().bind(new InetSocketAddress("127.0.0.1",7979));
SelectionKey acceptKey=ssc.register(selector,SelectionKey.OP_ACCEPT);
//System.out.println("通道就绪个数:"+selector.select());
int keysAdded=0;
while((keysAdded=selector.select())>0)
{
Set readyKeys=selector.selectedKeys();
Iterator i=readyKeys.iterator();
while(i.hasNext())
{
SelectionKey sk=(SelectionKey) i.next();
i.remove();
ServerSocketChannel nextReady= (ServerSocketChannel) sk.channel();
Socket s=nextReady.accept().socket();
InputStream din=s.getInputStream();
DataInputStream ds=new DataInputStream(din);
String str=ds.readLine();
while(str!=null)
{
System.out.println(str);
str=ds.readLine();
}
}
}
}
}
使用telnet连接上,输入字符回车,可以在控制台上看到输出