Netty实现一个群聊系统

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

public class Server {

    private final Integer port;

    public Server(Integer port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast(new ServerHandler());

                        }
                    });
            System.out.println("Server is ready");

            ChannelFuture cf = serverBootstrap.bind(this.port).sync();
            cf.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Server server = new Server(8080);
        server.run();
    }

}

ClientHandler


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;

public class ServerHandler extends SimpleChannelInboundHandler<String> {

    private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public void handlerAdded(ChannelHandlerContext context) {
        Channel channel = context.channel();
        channelGroup.writeAndFlush("【系统】" + channel.remoteAddress() + "上线了\n");
        synchronized (channelGroup) {
            channelGroup.add(channel);
        }
    }

    public void channelActive(ChannelHandlerContext context) {
        System.out.println("【log】" + context.channel().remoteAddress() + "上线了");
    }

    public void handlerRemoved(ChannelHandlerContext context) {
        System.out.println("【log】" + context.channel().remoteAddress() + "下线了");
        Channel channel = context.channel();
        synchronized (channelGroup) {
            channelGroup.remove(channel);
        }
        channelGroup.writeAndFlush("【系统】" + channel.remoteAddress() + "下线了\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext context, String s) {
        System.out.println("【log】" + context.channel().remoteAddress() + "发送消息:" + s);

        channelGroup.forEach(channel -> {
            if(channel != context.channel()) {
                channel.writeAndFlush("【用户】" + context.channel().remoteAddress() + "发送消息:" + s + "\n");
            } else {
                channel.writeAndFlush("【我】" + context.channel().remoteAddress() + "发送消息:" + s + "\n");
            }
        });
    }

    public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) {
        System.out.println("【error】" + context.channel().remoteAddress() + "发生异常");
    }
}

Client


import io.netty.bootstrap.Bootstrap;
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.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

public class Client {

    private final String ip;
    private final Integer port;

    public Client(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
    }

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

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new ClientHandler());
                        }
                    });

            System.out.println("Client is ready");
            Channel channel = bootstrap.connect(this.ip, this.port).sync().channel();

            Scanner scanner = new Scanner(System.in);
            String content = scanner.nextLine();
            while(!content.equals("")) {
                channel.writeAndFlush(content + "\r\n");
                content = scanner.nextLine();
            }
        } finally {
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Client client = new Client("localhost", 8080);
        client.run();
    }
}

ClientHandler


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

public class ClientHandler extends SimpleChannelInboundHandler<String> {

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

    public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) {
        context.close();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值