公司多有多个小程序客服功能,实现统一接入聊天
每个小程序通知接入的通知地址不一样,但接入流程逻辑一样,在接入时标识所属小程序
netty统一发送消息到页面websocket部分,要定义好自己业务需要的消息体
@Component
public class ChannelWechatNotice {
private static final Logger lg = LoggerFactory.getLogger(ChannelWechatNotice.class);
/**socketWxchat.put("message", JzWxchat);
* socketWxchat.put("type", "weixin");
* @param socketWxchat
*/
@Async
public void postSocketUser(Map<String,Object> socketWxchat) {
String jsonMsg=JsonUtil.getJsonLocalDataTime(socketWxchat);
// String jsonMsg=JSONUtils.toJSONString(socketWxchat);
lg.info("调用netty发送消息信息:" + jsonMsg);
try {
// 给指定用户发
// ChannelUser channelUser = ChannelConst.getChannelUser("1512312");
// if(channelUser==null) {
// lg.info("微信通知调用netty发送消息到userId:" + null);
// return;
// }
// 给所有在线用户发
Map<String, ChannelUser> channelMap = ChannelConst.channelMap;
for (Entry<String, ChannelUser> s : channelMap.entrySet()) {
Channel channel = s.getValue().getChannel();
channel.writeAndFlush(new TextWebSocketFrame(jsonMsg));
}
} catch (Exception e) {
e.printStackTrace();
}
}
netty集成部分,
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static final Logger logger = LoggerFactory.getLogger(ChatHandler.class);
/**
* 广播获取消息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (null != msg && msg instanceof FullHttpRequest) {
// 第一次必进这里,认为这里链接成功
FullHttpRequest request = (FullHttpRequest) msg;
String uri = request.uri();
Map paramMap = getUrlParams(uri);
// 身份识别和sysuser做处理
System.out.println("channelRead接收连接的的参数是:" + JsonUtil.getJson(paramMap));
if (uri.contains("?")&¶mMap.containsKey(ChannelConst.CONST_USERID)) {
String userId = paramMap.get(ChannelConst.CONST_USERID).toString();
String channelShortId = getChannelShortId(ctx);
ChannelUser cu = new ChannelUser(channelShortId, userId, ctx.channel());
ChannelConst.channelMap.put(userId, cu);
System.err.println("身份识别成功,客户端channelMap数量:" + ChannelConst.clients.size());
}else {
ctx.close();//不让他连接
System.err.println("去掉不正常的连接===========================================");
return ;
}
String newUri = uri.substring(0, uri.indexOf("?"));
request.setUri(newUri);
}
if(msg instanceof TextWebSocketFrame) {
TextWebSocketFrame frame = (TextWebSocketFrame) msg;
System.out.println("接收到客户端的消息:" + frame.text());
// 将接收到的消息发送到所有的客户端
for (Channel channel : ChannelConst.clients) {
// 注意所有的websocket数据都应该以TextWebSocketFrame进行封装
channel.writeAndFlush(
new TextWebSocketFrame("服务器接收的消息:" + LocalDateTime.now() + ",消息是:" + frame.text()));
}
}
// if(msg instanceof CloseWebSocketFrame) {
// logger.info("有退出的用户===========================================");
// }else {
// logger.info("有其他消息===========================================");
// }
super.channelRead(ctx, msg);
}
高仿微信的界面,可以发图片或文字,不同的客户由不同的客服接入聊天