惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
L
LangChain Blog
Jina AI
Jina AI
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
S
Secure Thoughts
T
The Exploit Database - CXSecurity.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 聂微东
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
C
Cyber Attacks, Cyber Crime and Cyber Security
Project Zero
Project Zero
T
Threat Research - Cisco Blogs
量子位
G
GRAHAM CLULEY
腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
CERT Recently Published Vulnerability Notes
The Hacker News
The Hacker News
C
Cisco Blogs
Scott Helme
Scott Helme
Spread Privacy
Spread Privacy
宝玉的分享
宝玉的分享
V
V2EX
博客园 - 三生石上(FineUI控件)
T
Tor Project blog
P
Proofpoint News Feed
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
Vulnerabilities – Threatpost
PCI Perspectives
PCI Perspectives
博客园_首页
L
LINUX DO - 最新话题
IT之家
IT之家
有赞技术团队
有赞技术团队
博客园 - Franky
Hacker News: Ask HN
Hacker News: Ask HN
Last Week in AI
Last Week in AI
The Cloudflare Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
美团技术团队
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题
AWS News Blog
AWS News Blog
S
Security Affairs
T
Tailwind CSS Blog

博客园 - 我的bug

项目引入同一jar包不同版本处理 【笔记】redis实现类 【笔记】vue中websocket心跳机制 【笔记】MySQL删除重复记录保留一条 oss上传实例 jquery实现图片点击旋转 IDEA卡顿解决方法 斐波那契数列 【笔记】接口发送数据及接收 【笔记】获取新浪财经最新的USDT-CNY的汇率 【笔记】Java 信任所有SSL证书(解决PKIX path building failed问题) 【笔记】jquery判断两个日期之间相差多少天 【笔记】spring定时器时间配置实例 【笔记】jquery加减乘除及科学计算法处理 string 日期相加和相减 sql查询慢原因及优化 java小算法复习 找出一组数字中出现最多的字符 【转载】js清空cookie
【笔记】websockt一对一聊天java部分
我的bug · 2019-10-22 · via 博客园 - 我的bug
@Configuration("otcChatWebSocketConfig")
@EnableWebSocket
public class OtcChatWebSocketConfig implements WebSocketConfigurer {

    public static final Logger log = LoggerFactory.getLogger(OtcChatWebSocketConfig.class);

    @Bean("otcChatHallHandler")
    public OtcChatHallHandler tradingKlineSocketHandler() {
        return new OtcChatHallHandler();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        log.debug("websocket handler 注册");
        registry.addHandler(tradingKlineSocketHandler(), "/otcChat").addInterceptors(new OtcChatHallSocketShake()).setAllowedOrigins("*");
        registry.addHandler(tradingKlineSocketHandler(), "/otcChat").addInterceptors(new OtcChatHallSocketShake()).withSockJS();
    }

}
package hry.app.otc.socket.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import hry.app.jwt.TokenUtil;
import hry.app.otc.model.OtcAppTransactionRemote;
import hry.app.otc.model.OtcChatMessageRemote;
import hry.app.otc.remote.RemoteNewAdvertisementService;
import hry.manage.remote.model.User;
import hry.util.common.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author <a href="mailto:HelloHeSir@gmail.com">HeC</a>
 * @date 2019/1/17 11:14
 */
@Component
@ServerEndpoint("/otcchat")
public class OtcChatHallHandler  extends TextWebSocketHandler {
    private final static Logger LOGGER = LoggerFactory.getLogger(OtcChatHallHandler.class);

    /* 以用户id作为key值 保存用户的session对象 */
    private static Map<String, WebSocketSession> map = new HashMap<String, WebSocketSession>(); // 保存用户和对应的session

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //已建立连接的用户
    private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();

    /**
     * 处理前端发送的文本信息
     * js调用websocket.send时候,会调用该方法
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        String content = message.getPayload();
        LOGGER.info("otcChat WebSocket收到的消息:" +content);
        if(!StringUtils.isEmpty(content)){

            JSONObject jsStr = JSONObject.parseObject(content);// 转换成json数据
            String cmd = jsStr.getString("cmd");
            String token = jsStr.getString("token");
            String to = jsStr.getString("to");
            String chatContent = jsStr.getString("chatContent");
            String type = jsStr.getString("type");

            User user = TokenUtil.getUser(token);
            String userName = "";
            if(user != null){
                userName = StringUtils.isEmpty(user.getNickNameOtc()) ? user.getEmail() : user.getNickNameOtc();
            }
            if("enter_chatting".equals(cmd)){ //进入聊天统计人数
                map.put(user.getCustomerId().toString(),session);
            }else if("ping".equals(cmd)){ //进入聊天统计人数
               System.out.println("otcchat ping");
            }else if ("chatting".equals(cmd)) { //聊天
                System.out.println("聊天");

                RemoteNewAdvertisementService remoteNewAdvertisementService = SpringUtil.getBean("remoteNewAdvertisementService");
                OtcAppTransactionRemote otcAppTransaction = remoteNewAdvertisementService.getOtcTransactionByNum(to);
                String  otherId= "";
                Long buyUserId = otcAppTransaction.getBuyUserId();
                Long sellUserId = otcAppTransaction.getSellUserId();
                if(buyUserId.equals(user.getCustomerId())){
                    otherId = sellUserId.toString();
                }else{
                    otherId = buyUserId.toString();
                }
                Map msgmap = new HashMap();
                msgmap.put("fromName", userName);
                msgmap.put("fromID", user.getCustomerId());
                msgmap.put("content", chatContent);
                msgmap.put("created", sdf.format(new Date()));
                msgmap.put("type", type);

                session.sendMessage(new TextMessage(JSONObject.toJSONString(msgmap)));
                if(map.get(otherId)!= null){
                    map.get(otherId).sendMessage(new TextMessage(JSONObject.toJSONString(msgmap)));
                }
            }else if("out_chatting".equals(cmd)){ //退出聊天室,统计人数
                map.remove(user.getCustomerId().toString(),session);
            }

        }

    }


    /**
     * 当新连接建立的时候,被调用
     * 连接成功时候,会触发页面上onOpen方法
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
      // users.add(session);
        //连接时推送数据
        JSONObject root = new JSONObject();
        root.put("type","hello");
        root.put("data","hello otc");
     //   session.sendMessage(new TextMessage(JSON.toJSONString(root)));
    }

    /**
     * 当连接关闭时被调用
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        if(map != null && !map.isEmpty()){
            Set<Map.Entry<String, WebSocketSession>> set=map.entrySet();
            Iterator<Map.Entry<String, WebSocketSession>> iterator=set.iterator();

            while(iterator.hasNext()){
                Map.Entry<String, WebSocketSession> entry=iterator.next();
                WebSocketSession value=entry.getValue();
                if(value.equals(session)){
                    LOGGER.info("用户id " + entry.getKey() + " Connection closed. Status: " + status);
                    iterator.remove();
                }
            }
        }
    }

    /**
     * 传输错误时调用
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String username = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
        if (session.isOpen()) {
            session.close();
        }
        LOGGER.debug("用户: " + username + " websocket connection closed......");
        users.remove(session);
    }

    /**
     * 广播发送消息方法。
     * @param message
     */
    public void sendAllMessage(String message) {
        try {
            OtcChatMessageRemote chat = JSON.parseObject(message, OtcChatMessageRemote.class);
            RemoteNewAdvertisementService remoteNewAdvertisementService = SpringUtil.getBean("remoteNewAdvertisementService");
            OtcAppTransactionRemote otcAppTransaction = remoteNewAdvertisementService.getOtcTransactionById(chat.getOrderId().toString());
            String  otherId= "";
            Long buyUserId = otcAppTransaction.getBuyUserId();
            Long sellUserId = otcAppTransaction.getSellUserId();
            if(buyUserId.equals(chat.getFromID())){
                otherId = sellUserId.toString();
            }else{
                otherId = buyUserId.toString();
            }
            Map msgmap = new HashMap();
            msgmap.put("fromName", chat.getFromName());
            msgmap.put("fromID", chat.getFromID());
            msgmap.put("content", chat.getContent());
            msgmap.put("created", sdf.format(new Date()));
            msgmap.put("type", 3);

            if(map.get(chat.getFromID())!= null) {
                map.get(chat.getFromID()).sendMessage(new TextMessage(JSONObject.toJSONString(msgmap)));
            }
            if(map.get(otherId)!= null){
                map.get(otherId).sendMessage(new TextMessage(JSONObject.toJSONString(msgmap)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}