乐趣区

关于netty:基于netty的基础小案例

server 端代码
import com.chinadaas.bio.chinadaasbio.netty.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class Server {public static void main(String[] args) throws InterruptedException {NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 定义服务端启动类
            ServerBootstrap start = new ServerBootstrap()
                    .group(boosGroup, workerGroup) // 设置两个线程组
                    .channel(NioServerSocketChannel.class) // 应用 nioServer
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列失去的链接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 设置放弃流动连贯状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {  // 创立一个通道测试对象(匿名对象)@Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    });

            System.out.println("服务器 is ready");
            // 绑定一个端口 并且同步生成一个 ChannelFuture
            // 启动服务器(并绑定端口)ChannelFuture channelFuture = start.bind(8886).sync();
            // 对敞开通道进行监听
            channelFuture.channel().closeFuture().sync();} catch (Exception e) {e.printStackTrace();
        } finally {boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();}
    }
}
client 端代码

import com.chinadaas.bio.chinadaasbio.netty.handler.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {public static void main(String[] args) {NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {Bootstrap bootstrap = new Bootstrap()
                    .group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {socketChannel.pipeline().addLast(new ClientHandler());
                        }
                    });

            System.out.println("客户端 is ready");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8886).sync();
            // 敞开通道进行监听
            channelFuture.channel().closeFuture().sync();}catch (Exception e){e.printStackTrace();
        }finally {workerGroup.shutdownGracefully();
        }
    }
}
serverHandler 代码
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;


public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("有异样");
        ctx.close();}

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("服务器收到的音讯:" + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("客戶端的地址:" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.writeAndFlush(Unpooled.copiedBuffer("hello 客户端", CharsetUtil.UTF_8));
    }
}
clientHandler 代码
public class ClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 通道就绪后所触发的办法
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {ctx.writeAndFlush(Unpooled.copiedBuffer("hello 服务器", CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("客户端收到音讯:" + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器的地址:" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { }

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

}
退出移动版