import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
System.out.println("server received: " + byteBuf.toString(CharsetUtil.UTF_8));
ctx.write(byteBuf);
}
}
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelInitializer
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import java.io.IOException
import java.net.InetSocketAddress
public class EchoServer {
private final int port
public EchoServer(int port) {
this.port = port
}
public static void main(String[] args) throws Exception {
int port = 60000
new EchoServer(port).start()
}
public void start() throws Exception {
NioEventLoopGroup group = new NioEventLoopGroup()
try {
ServerBootstrap b = new ServerBootstrap()
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler())
}
})
ChannelFuture f = b.bind().sync()
System.out.println(EchoServer.class.getSimpleName() + " started listen on " + f.channel().localAddress())
f.channel().close().sync()
} finally {
group.shutdownGracefully().sync()
}
}
}