Netty-4聊天室

客户端:

public class ChatClient {

    public static void main(String[] args) {
        //事件循环组
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            //客户端的启动
            Bootstrap bootstrap = new Bootstrap();
            //处理事件,反射创建channel实例,处理的handler
            bootstrap.group(eventExecutors).channel(NioSocketChannel.class).
                    handler(new ChatInitializer());
            //绑定端口号
            Channel channel = bootstrap.connect("127.0.0.1", 8991).sync().channel();
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                channel.writeAndFlush(br.readLine() + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //异常发生退出
            eventExecutors.shutdownGracefully();
        }
    }
}

public class ChatInitializer extends ChannelInitializer <SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
//        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8), new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new ChatClientHandler());
    }
}

public class ChatClientHandler extends SimpleChannelInboundHandler <String> {

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

服务器:

public class ChatServer {

    public static void main(String[] args) {
        EventLoopGroup boosGrop = new NioEventLoopGroup();
        EventLoopGroup workGrop = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(boosGrop, workGrop).channel(NioServerSocketChannel.class).
                    childHandler(new ChatInitializer());
            ChannelFuture channelFuture = serverBootstrap.bind(8991).sync();
            ChannelFuture channelFuture1 = channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boosGrop.shutdownGracefully();
            workGrop.shutdownGracefully();
        }
    }
}

public class ChatInitializer extends ChannelInitializer <SocketChannel> {


    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
//        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8), new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new ChatHandler());
    }
}

public class ChatHandler extends SimpleChannelInboundHandler <String> {

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


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //转播消息
        CHANNELS.forEach((t) -> {
            if (!t.equals(ctx.channel())) {
                t.writeAndFlush(LocalDateTime.now() + "\r\n" + msg);
            } else {
                t.writeAndFlush(LocalDateTime.now() + "[自己]" + "\r\n" + msg);
            }
        });
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        CHANNELS.writeAndFlush("时间" + LocalDateTime.now() + channel.remoteAddress() + "加入" + "\r\n");
        CHANNELS.add(channel);
    }

    //自动触发channelGroup.remove方法
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        CHANNELS.writeAndFlush("时间" + LocalDateTime.now() + ctx.channel().remoteAddress() + "离开" + "\r\n");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        CHANNELS.writeAndFlush("时间" + LocalDateTime.now() + ctx.channel().remoteAddress() + "上线" + "\r\n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        CHANNELS.writeAndFlush("时间" + LocalDateTime.now() + ctx.channel().remoteAddress() + "下线" + "\r\n");
    }

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


}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值