前言:
接到了一个新人培训的第一阶段计划,需要用到netty框架,由于本人之前没什么接触过netty。这里写下博客记录一下学习过程咯。
传统IO
话不多说吧 先上个栗子:
public class OioServer {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
//线程池
ExecutorService pools=Executors.newCachedThreadPool();
ServerSocket server=new ServerSocket(10101);
System.out.println("服务器启动");
while (true){
//等待连接阻塞
final Socket socket=server.accept();
System.out.println("来了一个新的客户端");
pools.execute(new Runnable() {
public void run() {
handler(socket);
}
});
}
}
private static void handler(Socket socket) {
try{
byte[] bytes=new byte[1024];
InputStream inputStream=socket.getInputStream();
while (true){
//读取数据的时候阻塞
int read=inputStream.read(bytes);
if (read!=-1){
System.out.println(new String(bytes,0,read));
}else {
break;
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
System.out.println("socket关闭");
socket.close();
}catch (Exception e0){
e0.printStackTrace();
}
}
}
}
传统的io阻塞在两个地方
1)等待连接 server.accept
2)读取数据部分 inputStream.read();
想要同时处理多条网络IO,需要借助多线程技术,一条网络IO对应一条线程。在并发量不大的情况下,可以采用该模式。据说Tomcat就是采用了这种一个线程对应一条网络IO的模式。
弊端 :
在多个用户同时访问服务器的时候的情况下需要创建太多太多的线程了。一条线程对应一个用户。导致服务器的并发量不会太高。
NIO
先介绍一下Nio的常用api:
Selector
Selector允许单线程处理多个 Channel。如果你的应用打开了多个连接(通道),但每个连接的流量都很低,使用Selector就会很方便。
要使用Selector,得向Selector注册Channel,然后调用它的select()方法。这个方法会一直阻塞到某个注册的通道有事件就绪。一旦这个方法返回,线程就可以处理这些事件,事件的例子有如新连接进来,数据接收等。
selector的创建
Selector selector = Selector.open();
channel.configureBlocking(false);
//与Selector一起使用时,Channel必须处于非阻塞模式下。这意味着不能将FileChannel与Selector一起使用,因为FileChannel不能切换到非阻塞模式。而套接字通道都可以。
SelectionKey key = channel.register(selector,
Selectionkey.OP_READ);//给channel注册了一个读事件,即该channel可读的时候就会通知selector
SelectionKey
SelectionKey 将准备好的channel中的SelectionKey拿出来判断类型,根据不同的类型我们再去做不同的处理
事件名 | 对应值 |
---|---|
服务端接收客户端连接事件 | SelectionKey.OP_ACCEPT(16) |
客户端连接服务端事件 | SelectionKey.OP_CONNECT(8) |
读事件 | SelectionKey.OP_READ(1) |
写事件 | SelectionKey.OP_WRITE(4) |
Channel实现
ServerSocketChannel
ServerSocketChannel 是一个可以监听新进来的TCP连接的通道,监听新进来的TCP连接
SocketChannel
SocketChannel 是一个连接到TCP网络套接字的通道,通过TCP读写网络中的数据
DatagramChannel
DatagramChannel 是一个能收发UDP包的通道,通过UDP读写网络中的数据
实际例子
public class NioServer {
//通道管理器
private Selector selector;
/**
* 获得一个ServerSocket通道,并对该通道做一些初始化的工作
* @param port 绑定的端口号
* @throws IOException
*/
public void initServer(int port) throws IOException {
// 获得一个ServerSocket通道
ServerSocketChannel serverChannel = ServerSocketChannel.open();
// 设置通道为非阻塞
serverChannel.configureBlocking(false);
// 将该通道对应的ServerSocket绑定到port端口
serverChannel.socket().bind(new InetSocketAddress(port));
// 获得一个通道管理器
this.selector = Selector.open();
//将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
//当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
}
/**
* 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
* @throws IOException
*/
@SuppressWarnings("unchecked")
public void listen() throws IOException {
System.out.println("服务端启动成功!");
// 轮询访问selector
while (true) {
//当注册的事件到达时,方法返回;否则,该方法会一直阻塞
selector.select();
// 获得selector中选中的项的迭代器,选中的项为注册的事件
Iterator ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next();
// 删除已选的key,以防重复处理
ite.remove();
handler(key);
}
}
}
private void handler(SelectionKey key) throws IOException {
//客户端连接事件
if (key.isAcceptable()) {
handlerAccept(key);
//通道可读事件
}else if (key.isReadable()){
handelerRead(key);
}
}
private void handelerRead(SelectionKey key) throws IOException {
// 服务器可读取消息:得到事件发生的Socket通道
SocketChannel channel = (SocketChannel) key.channel();
// 创建读取的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(10);
int read=channel.read(buffer);
if (read>0) {
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("服务端收到信息:" + msg);
ByteBuffer outBuffer = ByteBuffer.wrap("好的!".getBytes());
channel.write(outBuffer);// 将消息回送给客户端
}else {
System.out.println("客户端关闭");
key.channel();
}
}
private void handlerAccept(SelectionKey key) throws IOException {
ServerSocketChannel server = (ServerSocketChannel) key
.channel();
// 获得和客户端连接的通道
SocketChannel channel = server.accept();
// 设置成非阻塞
channel.configureBlocking(false);
System.out.println("新的客户端连接");
//在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ);
}
/**
* 启动服务端测试
* @throws IOException
*/
public static void main(String[] args) throws IOException {
NioServer server = new NioServer();
server.initServer(8000);
server.listen();
}
}
基本的注释我都标明了,然后的话先看完nio的每个api作用基本就能看懂这份代码的所实现的简单版基本NIO的服务器。
总结
Netty的底层实现就是依靠Nio来实现的,无非在此基础上加以两个线程池对于网络IO来进行处理,一个Worker线程池处理网络IO读取、一个Boss线程池对于网络IO连接的监听。