package org.wdzl.netty;
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.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.lang3.StringUtils;
import org.wdzl.SpringUtil;
import org.wdzl.enums.MsgActionEnum;
import org.wdzl.pojo.User;
import org.wdzl.services.UserServices;
import org.wdzl.utils.JsonUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 用于处理消息的handler
* 由于它的传输数据的载体是frame,这个frame 在netty中,是用于为websocket专门处理文本对象的,frame是消息的载体,此类叫:TextWebSocketFrame
*/
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
//用于记录和管理所有客户端的channel
public static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
//获取客户端所传输的消息
String content = msg.text();
//1.获取客户端发来的消息
DataContent dataContent = JsonUtils.jsonToPojo(content, DataContent.class);
Integer action = dataContent.getAction();
Channel channel = ctx.channel();
//2.判断消息类型,根据不同的类型来处理不同的业务
if(action == MsgActionEnum.CONNECT.type){
//2.1 当websocket 第一次open的时候,初始化channel,把用的channel 和 userid 关联起来
String senderId = dataContent.getChatMsg().getSenderId();
UserChanelRel.put(senderId,channel);
//测试
for (Channel c: users) {
System.out.println(c.id().asLongText());
}
UserChanelRel.output();
} else if(action == MsgActionEnum.CHAT.type){
//2.2 聊天类型的消息,把聊天记录保存到数据库,同时标记消息的签收状态[未签收]
ChatMsg chatMsg = dataContent.getChatMsg();
String msgContent = chatMsg.getMsg();
String senderId = chatMsg.getSenderId();
String receiverId = chatMsg.getReceiverId();
//保存消息到数据库,并且标记为未签收
UserServices userServices = (UserServices) SpringUtil.getBean("userServicesImpl");
String msgId = userServices.saveMsg(chatMsg);
chatMsg.setMsgId(msgId);
DataContent dataContentMsg = new DataContent();
dataContentMsg.setChatMsg(chatMsg);
//发送消息
Channel receiverChannel = UserChanelRel.get(receiverId);
if<
netty实现实时聊天
最新推荐文章于 2025-06-29 08:56:11 发布