cn.blankcat.websocket.handler.WebsocketHandler Maven / Gradle / Ivy
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);
}