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();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HumorChen99

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值