Netty实现TCP服务

客户端

package com.cnblogs.javalouvre;

import static io.netty.util.CharsetUtil.UTF_8;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;

public class EchoClient {

    private static final Logger log = LoggerFactory.getLogger(EchoClient.class);
    private static final int   PORT = 5678;

    public static void main(String[] args) {
        new EchoClient().bind();
    }

    private void bind() {
        ChannelFuture channelFuture = null;
        final Bootstrap bootstrap = new Bootstrap();
        final EventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, Boolean.TRUE)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        final ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new LoggingHandler());
                        pipeline.addLast(new StringEncoder(UTF_8));
                        pipeline.addLast(new StringDecoder(UTF_8));
                        pipeline.addLast(new SimpleChannelInboundHandler<String>() {

                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                log.info("客户端收到消息:{}", msg);
                            }

                        });
                    }
                });
        try {
            channelFuture = bootstrap.connect("127.0.0.1", PORT).sync();
            channelFuture.addListener(new ChannelFutureListener() {
                
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        log.info("客户端启动失败");
                    }
                }
            });

            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String text;
            while (!"quit".equalsIgnoreCase(text = bufferedReader.readLine())) {
                channelFuture.channel().writeAndFlush(text);
            }

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

}

服务端

package com.cnblogs.javalouvre;

import static java.nio.charset.StandardCharsets.UTF_8;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;

public class EchoServer {

    private static final Logger log = LoggerFactory.getLogger(EchoServer.class);
    private static final int   PORT = 5678;

    public static void main(String[] args) {
        new EchoServer().bind();
    }

    private void bind() {
        final ServerBootstrap bootstrap   = new ServerBootstrap();
        final EventLoopGroup  parentGroup = new NioEventLoopGroup(),
                              childGroup  = new NioEventLoopGroup();
        bootstrap.group(parentGroup, childGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        final ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new LoggingHandler());
                        pipeline.addLast(new StringEncoder(UTF_8));
                        pipeline.addLast(new StringDecoder(UTF_8));
                        pipeline.addLast(new SimpleChannelInboundHandler<String>() {

                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                log.info("服务器收到消息:{}", msg);

                                ctx.writeAndFlush("Hello " + msg);
                            }

                        });
                    }
                });
        try {
            final ChannelFuture channelFuture = bootstrap.bind(PORT).sync();

            channelFuture.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!channelFuture.isSuccess()) {
                        log.info("服务启动失败");
                    }
                }

            });

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            childGroup.shutdownGracefully();
            parentGroup.shutdownGracefully();
        }
    }

}
posted @ 2022-05-06 14:49  Bruce.Chang.Lee  阅读(5)  评论(0编辑  收藏  举报