天天看點

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實作群聊系統和私聊系統

繼續閱讀