使用nio作为服务端
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class TestNio {
private ByteBuffer readBuffer;
private Selector selector;
/**
* 初始化
*
*/
private void init() {
readBuffer = ByteBuffer.allocate(1024);
ServerSocketChannel servSocketChannel;
try {
// 获得一个ServerSocket通道
servSocketChannel = ServerSocketChannel.open();
// 设置通道为非阻
servSocketChannel.configureBlocking(false);
// 将该通道对应的ServerSocket绑定到port端口
servSocketChannel.socket().bind(new InetSocketAddress(8888));
// 获得一个通道管理器
selector = Selector.open();
//将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
//当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
servSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 监听
*/
private void listen() {
System.out.println("启动成功。。。");
// 轮询访问selector
while (true) {
try {
selector.select();
Iterator ite = selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next();
ite.remove();
handleKey(key);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
private void handleKey(SelectionKey key) throws IOException {
SocketChannel channel = null;
try {
if (key.isAcceptable()) {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
channel = serverChannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
channel = (SocketChannel) key.channel();
readBuffer.clear();
int count = channel.read(readBuffer);
if (count > 0) {
readBuffer.flip();
ByteBuffer response = ByteBuffer.wrap(new byte[] { 'r','e', 's', 'p', 'o', 'n', 's', 'e' });
byte[] request=new byte[7];
System.out.println(readBuffer.get(request));
while (response.hasRemaining()) {
channel.write(response);
}
} else {
channel.close();
}
}
} catch (Throwable t) {
t.printStackTrace();
if (channel != null) {
channel.close();
}
}
}
public static void main(String[] args) {
TestNio nioServer = new TestNio();
nioServer.init();
nioServer.listen();
}
}