EchoServer

  1. public class EchoServer {
  2. private final int port;
  3. public EchoServer(int port) {
  4. this.port = port;
  5. }
  6. public static void main(String[] args) throws InterruptedException {
  7. int port = 9999;
  8. EchoServer echoServer = new EchoServer(port);
  9. System.out.println("服务器即将启动");
  10. echoServer.start();
  11. System.out.println("服务器关闭");
  12. }
  13. public void start() throws InterruptedException {
  14. final EchoServerHandler serverHandler = new EchoServerHandler();
  15. // 线程组
  16. EventLoopGroup group = new NioEventLoopGroup();
  17. try {
  18. //服务端启动必备
  19. ServerBootstrap b = new ServerBootstrap();
  20. b.group(group)
  21. //指定使用NIO的通信模式
  22. .channel(NioServerSocketChannel.class)
  23. //指定监听端口
  24. .localAddress(new InetSocketAddress(port))
  25. .childHandler(new ChannelInitializer<SocketChannel>() {
  26. @Override
  27. protected void initChannel(SocketChannel ch) throws Exception {
  28. ch.pipeline().addLast(serverHandler);
  29. }
  30. });
  31. //异步绑定到服务器,sync()会阻塞到完成
  32. ChannelFuture f = b.bind().sync();
  33. //阻塞当前线程,直到服务器的ServerChannel被关闭
  34. f.channel().closeFuture().sync();
  35. } finally {
  36. group.shutdownGracefully().sync();
  37. }
  38. }
  39. }

EchoServerHandler

  1. @ChannelHandler.Sharable
  2. public class EchoServerHandler extends ChannelInboundHandlerAdapter {
  3. @Override
  4. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  5. ByteBuf in = (ByteBuf)msg;
  6. System.out.println("Server accept: "+in.toString(CharsetUtil.UTF_8));
  7. ctx.writeAndFlush(in);
  8. //ctx.close();
  9. }
  10. @Override
  11. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  12. cause.printStackTrace();
  13. ctx.close();
  14. }
  15. }