Java高手的30k之路|面试宝典|精通Netty(二)

实践应用

构建服务器和客户端

  • 掌握如何使用Netty构建TCP/UDP服务器和客户端,包括初始化、监听和连接。
  • 如何处理心跳机制,保持长连接的活跃。

TCP 服务器

1. 引入依赖

pom.xml文件中添加Netty依赖:

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.69.Final</version>
</dependency>
2. 创建服务器引导类
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TcpServer {
   

    private final int port;

    public TcpServer(int port) {
   
        this.port = port;
    }

    public void start() throws InterruptedException {
   
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
   
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
   
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
   
                     ch.pipeline().addLast(new TcpServerHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)
             .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
   
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
   
        int port = 8080; // 端口号
        new TcpServer(port).start();
    }
}
3. 创建服务器处理器
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TcpServerHandler extends ChannelInboundHandlerAdapter {
   

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
   
        // 处理收到的消息
        System.out.println("Server received: " + msg);
        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
   
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
   
        cause.printStackTrace();
        ctx.close();
    }
}

TCP 客户端

1. 创建客户端引导类
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TcpClient {
   

    private final String host;
    private final int port;

    public TcpClient(String host, int port) {
   
        this.host = host;
        this.port = port;
    }

    public void start() throws InterruptedException {
   
        EventLoopGroup group = new NioEventLoopGroup();
        try {
   
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<SocketChannel>() {
   
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
   
                     ch.pipeline().addLast(new TcpClientHandler());
                 }
             });

            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
   
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
   
        String host = "localhost";
        int port = 8080; // 端口号
        new TcpClient(host, port).start();
    }
}
2. 创建客户端处理器
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TcpClientHandler extends ChannelInboundHandlerAdapter {
   

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
   
        ctx.writeAndFlush("Hello Server!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
   
        System.out.println("Client received: " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
   
        cause.printStackTrace();
        ctx.close();
    }
}

UDP 服务器

1. 创建服务器引导类
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class UdpServer {
   

    private final int port;

    public UdpServer(int port) {
   
        this.port = port;
    }

    public void start() throws InterruptedException {
   
        EventLoopGroup group = new NioEventLoopGroup();
        try {
   
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioDatagramChannel.class)
             .option(ChannelOption.SO_BROADCAST, true)
             .handler(new ChannelInitializer<DatagramChannel>() {
   
                 @Override
                 protected void initChannel(DatagramChannel ch) throws Exception {
   
                     ch.pipeline().addLast(new UdpServerHandler());
                 }
             });

            b.bind(port).sync().channel().closeFuture().await();
        } finally {
   
            group.shutdownGracefully(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值