本篇简单介绍java基于高性能网络框架Netty的tcp通讯。
Netty
Netty的强大之处在于,它的高度抽象和封装。使用者无需关心内部实现。只需要修改相关handler类即可。
客户端
package tcp;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
public class TcpClient {
/* Server Ip */
public static String HOST = "127.0.0.1";
/* Server Port */
public static int PORT = 12340;
public static Bootstrap bootstrap = getBootstrap();
public static Channel channel = getChannel(HOST, PORT);
// 初始化 `Bootstrap`
public static final Bootstrap getBootstrap() {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class);
b.handler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
// 每个 `Channel` 都关联一个 `ChannelPi