All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.blankcat.websocket.handler.WebsocketHandler Maven / Gradle / Ivy

There is a newer version: 2.1.3
Show newest version
package cn.blankcat.websocket.handler;

import cn.blankcat.dto.websocket.WSPayload;
import cn.blankcat.websocket.WebsocketService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public interface WebsocketHandler {

    /**
     * 根据消息的data类型将该handler注册到websocket服务中
     * @param clazz 消息的data类型
     */
    default void register(Class clazz) {
        WebsocketService.CLASS_HANDLER_MAP.get(clazz).add(this);
    }

    /**
     * @param message websocket消息
     * @param clazz 消息的data类型
     * @return clazz类型的消息数据
     */
    default T toType(String message, Class clazz) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            WSPayload wsPayload = mapper.readValue(message, mapper.getTypeFactory().constructParametricType(WSPayload.class, clazz));
            return wsPayload.getData();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 实际处理websocket消息的方法
     * @param message websocket消息
     */
    void handle(String message);
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy