import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
public class ByteBufferTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ByteBuffer buf = ByteBuffer.allocate(256);
while(true) {
int c = System.in.read();
if(c==-1) {
break;
}
buf.put((byte)c);
if(c=='\n') {
//调用flip()使limit变为当前的position的值,position的值变为0
//为接下来从ByteBuffer读取做准备
buf.flip();
byte[] content = new byte[buf.limit()];
//从ByteBuffer中读取数据到byte数组中
buf.get(content);
System.out.println(new String(content));
System.out.println();
//position=0 , limit=capacity
//为写入数据到ByteBuffer中做准备
buf.clear();
}
// ScatteringByteChannel sbc = new ScatteringByteChannel() {
//
// @Override
// public boolean isOpen() {
// // TODO Auto-generated method stub
// return false;
// }
//
// @Override
// public void close() throws IOException {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public int read(ByteBuffer arg0) throws IOException {
// // TODO Auto-generated method stub
// return 0;
// }
//
// @Override
// public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
// // TODO Auto-generated method stub
// return 0;
// }
//
// @Override
// public long read(ByteBuffer[] arg0) throws IOException {
// // TODO Auto-generated method stub
// return 0;
// }
// };
}
}
private static void acceptConnections(int port) throws IOException {
//打开一个selector
Selector acceptSelector = SelectorProvider.provider().openSelector();
//SelectableChannel子类
ServerSocketChannel ssc = ServerSocketChannel.open();
//将其设置为 non-blocking状态,这样才能进行异步IO操作
ssc.configureBlocking(false);
//给ServerSocketChannel对应的socket绑定IP和端口
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia,port);
ssc.socket().bind(isa);
//将ServerSocketChannel注册到Selector上,返回对应的SelectionKey
SelectionKey acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
int keysAdded = 0;
//用select()函数来监控注册在Selector上的SelectableChannel
//返回值代表了有多少channel可以进行IO操作(ready for IO)
while((keysAdded=acceptSelector.select())>0) {
//selectedKeys()返回一个SelectionKey的集合
//其中每个SelectionKey代表了一个可以进行IO操作channel
//一个ServerSocketChannel可以进行IO操作意味着有新的TCP连接加入了
Set readyKeys = acceptSelector.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();
PrintWriter out = new PrintWriter(s.getOutputStream());
Date now = new Date();
out.println(now);
out.close();
}
}
}
}
后续会追加上更详细的总结和说明!