Java Netty伺服器客戶端聊天示範程式碼

HumoChen99發表於2020-11-18
  • 效果圖
    在這裡插入圖片描述
    在這裡插入圖片描述

  • 依賴

        <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();
        }
    }
}

相關文章