public class NettyServerTest {
public static void main(String [] args){
new NettyServerTest().bing();
}
private void bing(){
EventLoopGroup bossgroup = new NioEventLoopGroup();
EventLoopGroup workgroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossgroup,workgroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1024).childHandler(new NettyChildHandle());
try {
ChannelFuture cf = serverBootstrap.bind(9999).sync();
cf.channel().closeFuture().sync();
} catch (InterruptedException ignored) {
} finally {
bossgroup.shutdownGracefully();
workgroup.shutdownGracefully();
}
}
private class NettyChildHandle extends ChannelInitializer<socketchannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyServerHandle());
}
}}
public class NettyServerHandle extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
byte [] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
String body = new String(bytes,"UTF-8");
System.out.println("收到来自外星的命令"+body);
String currentTime = "hello".equals(body)?"my name is netty":"No";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}}