//1、启动Server,输入telnet命令:telnet localhost 8088,再输入任意字符
//为什么我-次只能发送一个字节?
public class NettyServer {
private int port=8088;
public static void main(String[] args) {
NettyServer server = new NettyServer();
server.run();
}
void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new SeverHandler());
}}
).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
}catch(Exception e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class SeverHandler extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf)msg;
try {
while(in.isReadable()) {
System.out.println((char)in.readByte());
System.out.flush();
}
}finally {
ReferenceCountUtil.release(msg);
}
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}