| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183 |
- package com.izouma.nineth.websocket;
- import com.alibaba.fastjson.JSON;
- import com.izouma.nineth.domain.PublicScreenChat;
- import com.izouma.nineth.domain.PurchaseLevel;
- import com.izouma.nineth.domain.User;
- import com.izouma.nineth.dto.PublicScreenChatExceptionMsg;
- import com.izouma.nineth.exception.BusinessException;
- import com.izouma.nineth.repo.PublicScreenChatRepo;
- import com.izouma.nineth.repo.UserRepo;
- import com.izouma.nineth.service.ContentAuditService;
- import com.izouma.nineth.service.PurchaseLevelService;
- import com.izouma.nineth.utils.ApplicationContextUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.stereotype.Service;
- import javax.websocket.*;
- import javax.websocket.server.PathParam;
- import javax.websocket.server.ServerEndpoint;
- import java.time.LocalDateTime;
- import java.util.Map;
- import java.util.Objects;
- import java.util.Set;
- import java.util.concurrent.ConcurrentHashMap;
- @Service
- @ServerEndpoint(value = "/websocket/public/screen/{nickName}/{userId}")
- @Slf4j
- public class PublicScreenChatWebsocket extends WebsocketCommon {
- /**
- * 当前在线的客户端map
- */
- private static final Map<String, Session> clients = new ConcurrentHashMap();
- private PublicScreenChatRepo publicScreenChatRepo;
- private final String PREFIX = "meta-chat:";
- private UserRepo userRepo;
- private PurchaseLevelService purchaseLevelService;
- private ContentAuditService contentAuditService;
- private void init() {
- if (Objects.isNull(publicScreenChatRepo)) {
- publicScreenChatRepo = (PublicScreenChatRepo) ApplicationContextUtil.getBean("publicScreenChatRepo");
- }
- if (Objects.isNull(userRepo)) {
- userRepo = (UserRepo) ApplicationContextUtil.getBean("userRepo");
- }
- if (Objects.isNull(purchaseLevelService)) {
- purchaseLevelService = (PurchaseLevelService) ApplicationContextUtil.getBean("purchaseLevelService");
- }
- if (Objects.isNull(contentAuditService)) {
- contentAuditService = (ContentAuditService) ApplicationContextUtil.getBean("contentAuditService");
- }
- }
- @OnOpen
- public void onOpen(@PathParam("nickName") String nickName, @PathParam("userId") String userId, Session session) {
- init();
- // 判断当前玩家是否在其他地方登陆
- if (clients.containsKey(PREFIX.concat(userId))) {
- String msg = String.format("已在别处登陆,sessionId为[%S],正在为您关闭本连接", session.getId());
- exceptionHandle(userId, new PublicScreenChatExceptionMsg(1, msg));
- try {
- log.info("关闭session连接");
- clients.get(PREFIX.concat(userId)).close();
- } catch (Exception e) {
- exceptionHandle(userId, new PublicScreenChatExceptionMsg(1, String.format("session close throw exception[%S]", e)));
- return;
- }
- }
- log.info("现在来连接的sessionId:" + session.getId() + "玩家id:" + userId + "玩家昵称" + nickName);
- clients.put(PREFIX.concat(userId), session);
- String format = String.format("玩家[%S][%S]进入大厅", userId, nickName);
- PublicScreenChat publicScreenChat;
- try {
- publicScreenChat = savePublicScreenChat(userId, format, true);
- } catch (Exception e) {
- String errMsg = String.format("玩家进入大厅,保存信息发生异常[%S]", e);
- exceptionHandle(userId, new PublicScreenChatExceptionMsg(2, errMsg));
- return;
- }
- sendMessageToOther(clients, JSON.toJSONString(publicScreenChat), PREFIX.concat(userId));
- }
- @OnError
- public void onError(Session session, Throwable error) {
- // 异常处理
- log.error(String.format("sessionId[%S]的服务端发生了错误:[%S]", session.getId(), error.getMessage()));
- }
- @OnClose
- public void onClose(@PathParam("nickName") String nickName, @PathParam("userId") String userId, Session session) {
- init();
- log.info(String.format("sessionId:[%S] userId:[%S] is closed", session.getId(), userId));
- String format = String.format("玩家[%S][%S]离开大厅", userId, nickName);
- PublicScreenChat publicScreenChat;
- try {
- publicScreenChat = savePublicScreenChat(userId, format, true);
- } catch (Exception e) {
- String errMsg = String.format("玩家离开大厅,保存信息发生异常[%S]", e);
- exceptionHandle(userId, new PublicScreenChatExceptionMsg(2, errMsg));
- return;
- }
- sendMessageToOther(clients, JSON.toJSONString(publicScreenChat), PREFIX.concat(userId));
- clients.remove(PREFIX.concat(userId));
- }
- @OnMessage
- public void onMessage(@PathParam("userId") String userId, String message) {
- init();
- if (StringUtils.isBlank(message)) {
- String errMsg = "Illegal parameter : message can not be null";
- exceptionHandle(userId, new PublicScreenChatExceptionMsg(4, errMsg));
- return;
- }
- if (!contentAuditService.auditText(message)) {
- savePublicScreenChat(userId, message, false);
- exceptionHandle(userId, new PublicScreenChatExceptionMsg(3, "消息包含非法内容"));
- return;
- }
- PublicScreenChat publicScreenChat;
- try {
- publicScreenChat = savePublicScreenChat(userId, message, true);
- } catch (Exception e) {
- String errMsg = String.format("玩家发送消息,保存信息发生异常[%S]", e);
- exceptionHandle(userId, new PublicScreenChatExceptionMsg(2, errMsg));
- return;
- }
- sendMessageToAll(clients, JSON.toJSONString(publicScreenChat), PREFIX.concat(userId));
- }
- /**
- * 给所有用户发消息
- *
- * @param clients 在线客户端
- * @param message 消息
- */
- public void sendMessageToAll(Map<String, Session> clients, String message, String userId) {
- PublicScreenChat publicScreenChat = JSON.parseObject(message, PublicScreenChat.class);
- Set<String> userIds = clients.keySet();
- userIds.forEach(id -> {
- try {
- publicScreenChat.setMyself(id.equals(userId));
- log.info(String.format("服务器给所有在线用户发送消息,当前在线人员为[%S]。消息:[%S]", id, JSON.toJSONString(publicScreenChat)));
- clients.get(id).getBasicRemote().sendText(JSON.toJSONString(publicScreenChat));
- } catch (Exception e) {
- log.error(String.format("send message [%S] to [%S] throw exception [%S]:", JSON.toJSONString(publicScreenChat), id, e));
- }
- });
- }
- private PublicScreenChat savePublicScreenChat(String userId, String messageInfo, boolean illegal) {
- User user = userRepo.findById(Long.parseLong(userId)).orElse(null);
- if (Objects.isNull(user)) {
- throw new BusinessException("用户信息不存在");
- }
- PublicScreenChat publicScreenChat = new PublicScreenChat();
- publicScreenChat.setUserId(userId);
- publicScreenChat.setAvatar(user.getAvatar());
- publicScreenChat.setNickname(user.getNickname());
- publicScreenChat.setLevel(user.getLevel());
- PurchaseLevel purchaseLevel = purchaseLevelService.findPurchaseLevelByLevel(publicScreenChat.getLevel());
- publicScreenChat.setRealm(purchaseLevel.getRealm());
- publicScreenChat.setTitle(purchaseLevel.getTitle());
- publicScreenChat.setMessageInfo(messageInfo);
- publicScreenChat.setTime(LocalDateTime.now());
- publicScreenChat.setIllegal(illegal);
- return publicScreenChatRepo.save(publicScreenChat);
- }
- private void exceptionHandle(String userId, PublicScreenChatExceptionMsg msg) {
- log.error(JSON.toJSONString(msg));
- // 推送消息给该玩家
- sendMessageTo(clients, JSON.toJSONString(msg), PREFIX.concat(userId));
- }
- }
|