天天看点

Netty由浅到深_第五章_Netty实现群聊系统和私聊系统

应用实例-群聊系统

  • 1)编写一个Netty群聊系统,实现服务器和客户端之间的数据简单通讯
  • 2)客户端:通过Channel可以无阻塞发送消息给其他所有用户,同时可以接受其他用户发送的消息(由服务器转发得到)
  • 3)服务器端:可以检测用户上线、离线,并实现消息的转发功能
package com.dd.netty.groupchat;

import com.dd.nio.groupchat.GroupChatClient;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class GroupChatServer {

    private int port ;//监听端口

    public GroupChatServer(int port){
        this.port = port;
    }

    public void run() throws InterruptedException {



        //创建bossGroup和WrokerGroup
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();//默认cpu核数乘以2个NioEventLoop
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            ChannelPipeline pipeline = socketChannel.pipeline();

                            //向pipeline加入一个解码器
                            pipeline.addLast("decoder",new StringDecoder());

                            //向pipeline加入编码器
                            pipeline.addLast("encode",new StringEncoder());

                            //加入自己的处理器
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });

            System.out.println("Netty服务器启动");

            ChannelFuture chanelFuture = bootstrap.bind(port).sync();

            //监听关闭事件
            chanelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        new GroupChatServer(7000).run();
    }
}

           
package com.dd.netty.groupchat;

import com.sun.org.apache.bcel.internal.generic.NEW;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.*;

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
    /*
    //自己定义一个channel  list   上线就加入  下线就去掉。上古写法,操作比较麻烦
    public static List<Channel> channels = new ArrayList<Channel>();
    */

    /*
    私服聊天实现
    使用一个hashMap 管理
      public static Map<String,Channel> map = new HashMap<>()
       channelGroup.add("id",channel);
     */





    /*
    定义一个Channel 组,管理所有的channel
     */
    //GlobalEventExecutor.INSTANCE是一个全局事件执行器,是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Channel channel = ctx.channel();

        //这时我们要遍历ChannelGroup,根据不同情况,会送不同消息
        channelGroup.forEach(ch->{
            if (channel != ch){
                ch.writeAndFlush("[客户]"+channel.remoteAddress()+" "+sdf.format(new Date())+":"+msg);
            }else {//回显自己发送的消息
                ch.writeAndFlush("[自己]自己发送的消息: "+sdf.format(new Date())+":"+msg);
            }
        });

    }

    //表示连接建立,第一个被执行
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();

        //将该客户加入聊天的信息推送给其他在线的客户端
        channelGroup.writeAndFlush("客户端"+channel.remoteAddress()+"加入聊天\n");

        //将当前channel加入到ChannelGroup
        channelGroup.add(channel);
    }


    //表示断开连接
    //该方法执行,会导致   channelGroup.remove(channel);   所以不用写此句代码
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        //将该客户加入聊天的信息推送给其他在线的客户端
        channelGroup.writeAndFlush("客户端"+channel.remoteAddress()+"离线了\n");
    }

    //表示channel处于活动状态  提示XX上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"上线了");
    }

    //表示channel处于非活动状态   提示XX下线了
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"离线了");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

           
package com.dd.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class GroupChatClient {

    private final String HOST_IP;
    private final int PORT;

    public GroupChatClient(String host,int port){
        this.HOST_IP = host;
        this.PORT = port;
    }

    public void run() throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //向pipeline加入一个解码器
                            pipeline.addLast("decoder",new StringDecoder());

                            //向pipeline加入编码器
                            pipeline.addLast("encode",new StringEncoder());

                            //加入自己的处理器
                            pipeline.addLast(new GroupChatClientHandler());

                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect(HOST_IP, PORT).sync();
            if (channelFuture.isSuccess()){
                System.out.println("===="+channelFuture.channel().localAddress()+"====");

                //客户端需要输入信息,创建一个扫描器
                Scanner scanner = new Scanner(System.in);
                while (scanner.hasNextLine()){
                    String msg = scanner.nextLine();

                    //通过channel发送数据到服务器端
                    channelFuture.channel().writeAndFlush(msg+"\r\n");
                }
            }
        }finally {
            eventExecutors.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new GroupChatClient("127.0.0.1",7000).run();
    }
}

           
package com.dd.netty.groupchat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println(s.trim());
    }
}

           

私聊

Netty由浅到深_第五章_Netty实现群聊系统和私聊系统

继续阅读