Java Netty服务器客户端聊天示范代码

  • 效果图
    在这里插入图片描述
    在这里插入图片描述

  • 依赖

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.36.Final</version>
        </dependency>
  • 客户端代码
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class client {

    public static void main(String[] args) {
        final ExecutorService pool = Executors.newSingleThreadExecutor();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>(){
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline=socketChannel.pipeline();
                            pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                                @Override
                                public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                                    System.out.println("服务器已上线!!!");
                                    pool.execute(new Runnable() {
                                        public void run() {
                                            Scanner scanner=new Scanner(System.in);
                                            String text="";
                                            while (true){
                                                text=scanner.nextLine();
                                                if(text.toLowerCase().equals("bye")){
                                                    ctx.close();
                                                }
                                                ctx.writeAndFlush(Unpooled.copiedBuffer(text+ "\r\n ", Charset.forName("utf-8")));
                                                System.out.println(new Date().toString()+" 【客户端】:"+text);
                                            }
                                        }
                                    });
                                }
                                @Override
                                protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
                                    String str=byteBuf.toString(CharsetUtil.UTF_8);
                                    System.out.println(new Date().toString()+"【服务器】:"+str);
                                }
                                @Override
                                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                    super.channelInactive(ctx);
                                    System.out.println("连接断开!!!");
                                    System.exit(0);
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

                                }
                            });
                        }
                    }); //自定义一个初始化类

            ChannelFuture channelFuture = bootstrap.connect("localhost", 7000).sync();
            System.out.println("客户端已启动");
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }


    }
}
  • 服务器端代码
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class server {
    public static void main(String[] args) {
        final ExecutorService pool = Executors.newSingleThreadExecutor();
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(3);
        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
                @Override
                public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                    System.out.println("客户端已上线!!!");
                    pool.execute(new Runnable() {
                        public void run() {
                            Scanner scanner=new Scanner(System.in);
                            String text="";
                            while (true){
                                text=scanner.nextLine();
                                if(text.toLowerCase().equals("bye")){
                                    ctx.close();
                                }
                                ctx.writeAndFlush(Unpooled.copiedBuffer(text+ "\r\n ", Charset.forName("utf-8")));
                                System.out.println(new Date().toString()+" 【服务器】:"+text);
                            }
                        }
                    });

                }

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
                    String str=byteBuf.toString(CharsetUtil.UTF_8);
                    System.out.println(new Date().toString()+"【客户端】:"+str);
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    super.channelInactive(ctx);
                    System.out.println("连接断开!!!");
                    System.exit(0);
                }
                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

                }
            }); //自定义一个初始化类


            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            System.out.println("服务器已启动");
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
posted @ 2020-11-18 17:26  HumorChen99  阅读(0)  评论(0编辑  收藏  举报  来源