[Notes] websockt one chat java part

@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:[email protected]">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>();// save the user and the corresponding session

    the SimpleDateFormat the SimpleDateFormat new new SDF = Private ( "the MM-dd-YYYY HH: mm: SS"); 

    // user connection established
    private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();

    /**
     * Sending text information processing front end 
     * call websocket.send JS when the method is called 
     * @param the session 
     * @param Message 
     * @throws Exception 
     * / 
    @Override 
    protected void handleTextMessage (WebSocketSession the session, TextMessage Message) throws Exception { 

        String Content message.getPayload = (); 
        logger.info:; ( "otcChat WebSocket message received" Content +) 
        (! StringUtils.isEmpty (Content)) {IF 

            the JSONObject jsStr = JSONObject.parseObject (Content); // converted into json data 
            String cmd = jsStr.getString ( "cmd"); 
            String = jsStr.getString token ( "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)));
     * @param the session
     *
     * when the connection is successful, the method will trigger onOpen the page
     * When the new connection is established, to be called
    / **
    }
        }
            }
                }
            }else if("out_chatting".equals(cmd)){ //退出聊天室,统计人数
                map.remove(user.getCustomerId().toString(),session);



 
     * @throws Exception 
     * / 
    @Override 
    public void afterConnectionEstablished (WebSocketSession the session) throws Exception { 
      // users.add (the session); 
        // push data connection 
        JSONObject the JSONObject new new = the root (); 
        root.put ( "type", "Hello"); 
        root.put ( "Data", "Hello OTC"); 
     // session.sendMessage (new new TextMessage (JSON.toJSONString (the root)) ); 
    } 

    / ** 
     * when the connection is closed is called 
     * 
     * @param the 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();
        }
    }

}

  

Guess you like

Origin www.cnblogs.com/mybug/p/11718585.html