Netty(二):服務端客戶端例項分析
阿新 • • 發佈:2019-02-02
package com.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Created by zhangtong on 2017/8/14.
*/
public class NettyServer {
private int port;
private NettyServer(int port) {
this.port = port;
}
private void runServer() throws Exception {
// EventLoopGroup是用來處理IO操作的多執行緒事件迴圈器
// bossGroup 接收連線請求
EventLoopGroup parentGroup = new NioEventLoopGroup();
// workerGroup 處理已經收到的請求
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
// 服務啟動器
ServerBootstrap sb = new ServerBootstrap();
sb.group(parentGroup, childGroup)
//配置 Channel
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 註冊handler
ch.pipeline().addLast(new ServerHandler());
}
})
// 設定服務端接受連線的佇列長度,如果佇列已滿,客戶端連線將被拒絕
.option(ChannelOption.SO_BACKLOG, 128)
// 心跳保活
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 繫結埠,啟動伺服器
ChannelFuture f = sb.bind(port).sync();//.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
// 一直等待直到伺服器 socket 關閉
f.channel().closeFuture().sync();
} finally {
// 將所有的event loop都關閉
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new NettyServer(9999).runServer();
System.out.println("over");
}
}