Java Netty服务器客户端聊天示范代码
  TEZNKK3IfmPf 2023年11月13日 29 0
  • 效果图
    Java Netty服务器客户端聊天示范代码
    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();
        }
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   19天前   43   0   0 java
TEZNKK3IfmPf