Netty版本 简单聊天室

Server服务器

public class Server {

    public static void main(String[] args){


        //1.创建两个线程组

        //用于处理服务器端接收客户端连接
        NioEventLoopGroup pGroup = new NioEventLoopGroup();

        //用于进行网络通信
        NioEventLoopGroup cGroup = new NioEventLoopGroup();


        try {

            //2.创建辅助工具类,用于服务器通道的配置
            ServerBootstrap b = new ServerBootstrap();

            //绑定两个线程组
            b.group(pGroup, cGroup)

                    //指定NIO模式
                    .channel(NioServerSocketChannel.class)

                    //设置tcp缓冲区队列
                    .option(ChannelOption.SO_BACKLOG, 1024)

                    //设置发送缓冲大小
                    .option(ChannelOption.SO_SNDBUF, 32 * 1024)

                    //设置接收缓冲大小
                    .option(ChannelOption.SO_RCVBUF, 32 * 1024)

                    //保持连接
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {

                            //3.配置接收方法的处理
                            sc.pipeline().addLast(new ServerHandler());
                        }
                    });


            //绑定端口号
            b.bind(3333).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

            pGroup.shutdownGracefully();

            cGroup.shutdownGracefully();
        }
        }



}


服务器信息处理


class ServerHandler extends ChannelInboundHandlerAdapter{

    public static ArrayList channelHandlerContexts = new ArrayList<>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if(!channelHandlerContexts.contains(ctx))
        {
            channelHandlerContexts.add(ctx);
        }



        //读取msg信息 并且写回给客户端
        ByteBuf buf = (ByteBuf) msg ;

        byte[] req = new byte[buf.readableBytes()];

        buf.readBytes(req);

        String body = new String(req,"utf-8");

        String response = "返回给客户端的响应: " + body;

        System.out.println("Server: " + body);



        //写回响应
        for (ChannelHandlerContext ctx1:channelHandlerContexts  ) {
               if(!ctx1.equals(ctx))
               {
                   ctx1.writeAndFlush(
                           //   创建一个新的big-endian缓冲区,其内容是指定array编码的指定子区域charset。
                           Unpooled.copiedBuffer(response.getBytes())
                   );
               }
        }






    }


客户端



public class Client {


    public static void main(String[] args) throws InterruptedException {





        NioEventLoopGroup group  = new NioEventLoopGroup();


        Bootstrap b = new Bootstrap();

        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new StringDecoder());
                        sc.pipeline().addLast(new ClientHandler());
                    }
                });

        ChannelFuture cf = b.connect("127.0.0.1", 3333).sync();


        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext())
        {

            cf.channel().writeAndFlush(Unpooled.wrappedBuffer(  scanner.nextLine().getBytes()));
        }



        // 等待客户端端口号关闭
        cf.channel().closeFuture().sync();

        group.shutdownGracefully();

    }



}

客户端处理信息


class ClientHandler extends SimpleChannelInboundHandler{


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {



        System.out.println("client: " + msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }


}

你可能感兴趣的:(Netty版本 简单聊天室)