Netty+SpringBoot+FastDFS+Html5实现聊天App,项目介绍。
Netty+SpringBoot+FastDFS+Html5实现聊天App,项目github链接。
本章主要讲的是聊天App_PigChat中关于聊天功能的实现。
移除方法与处理异常方法的重写
在ChatHandler中重写其移除channel的方法handlerRemoved,以及处理异常的方法exceptionCaught。
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
String channelId = ctx.channel().id().asShortText();
System.out.println("客户端被移除,channelId为:" + channelId);
// 当触发handlerRemoved,ChannelGroup会自动移除对应客户端的channel
users.remove(ctx.channel());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
// 发生异常之后关闭连接(关闭channel),随后从ChannelGroup中移除
ctx.channel().close();
users.remove(ctx.channel());
}
定义消息的实体类
public class ChatMsg implements Serializable {
private static final long serialVersionUID = 3611169682695799175L;
private String senderId; // 发送者的用户id
private String receiverId; // 接受者的用户id
private String msg; // 聊天内容
private String msgId; // 用于消息的签收
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;