Netty realizes group chat

Time:2020-5-21

[overview]

Implement a group chat tool. The client messages participating in the chat are broadcast through the server.

It mainly consists of two parts: chat server and chat client.

Chat server function overview:

1. Monitor the access and disconnection of all clients

2. When client a accesses the chat room, send the access message to other clients except client a

3. When client a exits the chat room, send the exit message to other clients except client a

4. When client a sends a message to the chat room, forward the message to other clients except client a

Chat client function overview:

1. Send message to chat server

2. Receive all messages sent by chat server

[POM dependence]

io.netty
            netty-all
            4.1.36.Final
        
        
        
            org.projectlombok
            lombok
            1.18.6
            provided

[server initiator chatServer]

package com.test.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 *Group chat server
 *
 */
public class ChatServer {
    private final int port;

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

    public void start() throws InterruptedException {
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() {

                protected void initChannel(SocketChannel sc) throws Exception {
                    ChannelPipeline pipeline = sc.pipeline();
                    //Add a row based decoder
                    pipeline.addLast(new LineBasedFrameDecoder(2048));
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new ChatServerHandler());
                }

            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println ("server started");
            future.channel().closeFuture().sync();
        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ChatServer(8888).start();
    }
}

 

【ChatServerHandler】

 

package com.test.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 *Handle various situations of chat server
 *
 */
public class ChatServerHandler extends ChannelInboundHandlerAdapter {
    //Create a channelgroup, which is a thread safe collection containing all active channels connected to the current server
    //Globaleventexecutor is a single instance, single thread eventexecutor to ensure the processing of all channels in the current group
    //Thread is the same thread
    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //As long as a client channel sends a message to the current server, the execution of this method will be triggered
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //Get the channel to send the message to the server
        Channel channel = ctx.channel();
        //This is to broadcast messages to all client channels in the group
        //The message sent to oneself is different from the message sent to everyone
        group.forEach(ch -> {
            if (ch != channel) {
                ch.writeAndFlush(channel.remoteAddress() + ":" + msg + "\n");
            } else {
                channel.writeAndFlush("me:" + msg + "\n");
            }
        });
    }

    //This method will be executed as long as there is a successful connection between the client channel and the server
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //Get the channel connected to the server successfully
        Channel channel = ctx.channel();
        System.out.println ( channel.remoteAddress () + "--- online");
        group.writeAndFlush ( channel.remoteAddress () + "--- online \ n");
        //Add the current channel to the group
        group.add(channel);
    }

    //As long as a client channel disconnects from the server, this method will be executed
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //Get the current channel to disconnect
        Channel channel = ctx.channel();
        System.out.println ( channel.remoteAddress () + "------ offline");
        group.writeAndFlush ( channel.remoteAddress () + "offline, current online number:"+ group.size () + "\n");

        //All channels in the group are active. Once a channel is no longer active,
        //Group will automatically kick it out of the collection, so the following statement does not need to be written
        //The application scenario of the remove () method is to use the
        // group.remove(channel);
    }

    /**
     *The execution of this method will be triggered when the data in the channel is abnormal during processing
     *
     *@ param CTX context
     *Exception object of @ param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

[Client startup class chatclient]

package com.test.client;

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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *Group chat client
 *
 */
public class ChatClient {
    private final String host;

    private final int port;

    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new LineBasedFrameDecoder(2048));
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new ChatClientHandler());
                }
            });
            ChannelFuture future = bootstrap.connect(host, port).sync();
            //Get keyboard input
            InputStreamReader is = new InputStreamReader(System.in, "UTF-8");
            BufferedReader br = new BufferedReader(is);
            //Write input to channel
            while (true) {
                // br.readLine Execute fill () method in () to get the input data. If not, it will block until the data is obtained
                future.channel().writeAndFlush(br.readLine() + "\r\n");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new ChatClient("127.0.0.1", 8888).start();
    }
}

【ChatClientHandler】

package com.test.client;

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

/**
 *Client processing
 *
 */
public class ChatClientHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println(s);
    }

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

[operation result]

[1. Start group chat server]

 

[2. Start group chat client 01]

 

 

 

[2. Start group chat client 02]

 

 

 

[3. Send message test]

 

 

 

[4. Offline test]