Java IO编程由浅入深 - 8 (bio实现C/S聊天室 3 )

目录

  1. Java IO编程由浅入深 - 1 (bio c/s架构实现)

  2. Java IO编程由浅入深 - 2(bio 基于字符串的消息编解码器)

  3. Java IO编程由浅入深 - 3 (bio 基于消息长度的解编码器)

  4. Java IO编程由浅入深 - 4 (bio http协议解编码器,实现http服务器)

  5. Java IO编程由浅入深 - 5 (项目架构重构)

  6. Java IO编程由浅入深 - 6 (bio实现C/S聊天室 1 )

  7. Java IO编程由浅入深 - 7 (bio实现C/S聊天室 2 )

  8. Java IO编程由浅入深 - 8 (bio实现C/S聊天室 3 )

  9. Java IO编程由浅入深 - 9 (bio实现http升级到websocket )

  10. Java IO编程由浅入深 - 10 (bio 基于websocket的心跳检测实现 )

对Message对象进行细分,拆分成以下对象

TextMessage (数据为文本内容)
BinaryMessage(数据为二进制)
StreamMessage(数据为流数据)
PingMessage(ping消息,对应必须响应pong)
PongMessage(pong消息)

编写CsServerMessageHandler,管理客户端与分发消息

package com.lhstack.example.handler;

import com.lhstack.bio.channel.Channel;
import com.lhstack.bio.channel.ChannelHandlerContext;
import com.lhstack.bio.channel.SimpleChannelAdapterHandler;
import com.lhstack.bio.codec.bs.TextMessage;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lhstack
 * 服务端
 */
public class CsServerMessageHandler extends SimpleChannelAdapterHandler<TextMessage> {

    private static final ConcurrentHashMap<String, Channel> MESSAGE_GROUP = new ConcurrentHashMap<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        MESSAGE_GROUP.forEach((k,v) ->{
            try {
                v.writeAndFlush(new TextMessage(String.format("%s: 欢迎客户端[%s],加入消息组",getCurrentFormatTime(),ctx.channel().id())));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        ctx.writeAndFlush(new TextMessage(String.format("%s: 你好,欢迎加入消息组",getCurrentFormatTime())));
        MESSAGE_GROUP.put(ctx.channel().id(),ctx.channel());
    }

    private String getCurrentFormatTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, TextMessage msg) throws Exception {
        MESSAGE_GROUP.forEach((k,v) ->{
            try {
                if(k.equals(ctx.channel().id())){
                    v.writeAndFlush(new TextMessage(String.format("%s: 你说: %s",getCurrentFormatTime(),msg.text())));
                }else{
                    v.writeAndFlush(new TextMessage(String.format("%s: 客户端[%s]说: %s",getCurrentFormatTime(),ctx.channel().id(),msg.text())));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void exceptionCatch(ChannelHandlerContext ctx, Throwable throwable) throws Exception {
        MESSAGE_GROUP.forEach((k,v) ->{
            try {
                if(!k.equals(ctx.channel().id())){
                    v.writeAndFlush(new TextMessage(String.format("%s: 客户端[%s]离开了消息组",getCurrentFormatTime(),ctx.channel().id())));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        MESSAGE_GROUP.remove(ctx.channel().id());
    }
}

编写客户端代码

public static void csMessageClient() throws Exception {
        BootStrap bootStrap = new BootStrap();
        Channel channel = bootStrap
                .group(new DefaultEventLoopGroup())
                .handler(new ChannelInitializeHandler() {
            @Override
            public void initializer(Channel ch) throws Exception {
                ch.pipeline()
                        .addLast(new CsMessageCodec())
                        .addLast(new CsClientMessageIdleStateHandler())
                        .addLast(new SimpleChannelAdapterHandler<TextMessage>() {
                            @Override
                            public void channelRead0(ChannelHandlerContext ctx, TextMessage msg) throws Exception {
                                System.out.println(new String(msg.getBody()));
                            }
                        });
            }
        }).connect(new InetSocketAddress("localhost", 8080));
        Scanner scanner = new Scanner(System.in);
        System.out.println("请发送消息");
        while(scanner.hasNext()){
            String msg = scanner.nextLine();
            channel.writeAndFlush(new TextMessage(msg,true));
        }
    }

测试一个客户端连接到服务端的效果

可以看到,客户端接收到了服务端响应的消息
在这里插入图片描述

这个时候我们加一个客户端,测试两个客户端的效果

客户端1收到了客户端2的上线消息,同时客户端2也收到了服务端响应的消息
客户端1
在这里插入图片描述

客户端2
在这里插入图片描述

测试客户端1和2分别发送消息

在这里插入图片描述
在这里插入图片描述
客户端1和2分别收到了消息

关闭客户端2

客户端1也收到了客户端2的离线通知
在这里插入图片描述

由此,我们实现了一个简单的群聊功能,同时附带了心跳检测功能

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值