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

私聊

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章