Donnie

不积跬步无以至千里

AI源码,Netty高可用版,估值一个亿

效果图

源码

服务端:

    public final class Server {
    
        public  static void main(String[] args) throws Exception {
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup,workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(LogLevel.INFO))
                        .childHandler(new ServerInitializer());
                ChannelFuture f = b.bind(8888);
                f.channel().closeFuture().sync();
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }

服务端Handler:

    @Sharable
    public class ServerHandler extends SimpleChannelInboundHandler<String> {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            // 为新连接发送庆祝
            ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
            ctx.write("It is " + new Date() + " now.\r\n");
            ctx.flush();
        }
    
        @Override
        public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
            // Generate and write a response.
            String response;
            boolean close = false;
            if (request.isEmpty()) {
                response = "请说点话吧 \r\n";
            } else if ("bye".equals(request.toLowerCase())||"再见".equals(request)) {
                response = "再见,下次见\r\n";
                close = true;
            } else {
                response =  request + " \r\n";
                response= response.replace("吗", "");
                response= response.replace("?", "!");
                response= response.replace("?", "!");
            }
    
            ChannelFuture future = ctx.write(response);
    
            if (close) {
                future.addListener(ChannelFutureListener.CLOSE);
            }
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) {
            ctx.flush();
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }


    public class ServerInitializer extends ChannelInitializer<SocketChannel> {
        private static final StringDecoder DECODER = new StringDecoder();
        private static final StringEncoder ENCODER = new StringEncoder();
    
        private static final ServerHandler SERVER_HANDLER = new ServerHandler();
    
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
    
            // Add the text line codec combination first,
            pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
            // the encoder and decoder are static as these are sharable
            pipeline.addLast(DECODER);
            pipeline.addLast(ENCODER);
    
            // and then business logic.
            pipeline.addLast(SERVER_HANDLER);
        }
    } 

客户端:

        public final class Client {
        public static void main(String[] args) throws Exception {
            EventLoopGroup group = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap();
                b.group(group)
                        .channel(NioSocketChannel.class)
                        .handler(new ClientInitializer());
                Channel ch = b.connect("127.0.0.1",8888).sync().channel();
    
    
                ChannelFuture lastWriteFuture = null;
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                for (;;) {
                    String line = in.readLine();
                    if (line == null) {
                        break;
                    }
    
                    // Sends the received line to the server.
                    lastWriteFuture = ch.writeAndFlush(line + "\r\n");
    
                    // If user typed the 'bye' command, wait until the server closes
                    // the connection.
                    if ("bye".equals(line.toLowerCase())) {
                        ch.closeFuture().sync();
                        break;
                    }
                }
    
                // Wait until all messages are flushed before closing the channel.
                if (lastWriteFuture != null) {
                    lastWriteFuture.sync();
                }
            } finally {
                group.shutdownGracefully();
            }
        }
    }

客户端handler:

    @Sharable
    public class ClientHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.err.println(msg);
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
  
    public class ClientInitializer extends ChannelInitializer<SocketChannel> {
        private static final StringDecoder DECODER = new StringDecoder();
        private static final StringEncoder ENCODER = new StringEncoder();
    
        private static final ClientHandler CLIENT_HANDLER = new ClientHandler();
    
    
        @Override
        public void initChannel(SocketChannel ch) {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
            pipeline.addLast(DECODER);
            pipeline.addLast(ENCODER);
    
            pipeline.addLast(CLIENT_HANDLER);
        }
    }

哈哈哈,祝各位看观愚人节快乐!

赞赏支持