package com.walker.tcp.websocket; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.node.ObjectNode; import com.walker.infrastructure.utils.JsonUtils; import com.walker.infrastructure.utils.StringUtils; import com.walker.tcp.AuthenticateException; import com.walker.tcp.Constants; import com.walker.tcp.ProtocolException; import com.walker.tcp.Request; import com.walker.tcp.Response; import com.walker.tcp.protocol.StringProtocolResolver; import com.walker.tcp.util.WebSocketUtils; import java.util.Map; //public class WebsocketProtocolResolver extends AbstractProtocolResolver { public class WebsocketProtocolResolver extends StringProtocolResolver { public WebsocketProtocolResolver(){ this.setName("Websocket协议解析器【内置】"); this.setOrder(10); } @JsonIgnore @Override protected String onResolve(String source, int size) throws ProtocolException { if(StringUtils.isEmpty(source)){ // throw new IllegalArgumentException("请求原始数据不存在,无法解析"); return null; } // JSONObject json = JSONObject.parseObject(source); ObjectNode json = null; try { json = JsonUtils.jsonStringToObjectNode(source); } catch (Exception e) { throw new RuntimeException(e); } if(json == null || !json.has(WebSocketUtils.WEB_SOCKET_KEY_PROTOCOL)){ throw new IllegalArgumentException("非法报文格式,请使用json,并带有protocol属性"); } return json.get(WebSocketUtils.WEB_SOCKET_KEY_PROTOCOL).asText(); } @JsonIgnore @Override protected Response doCreateOneResponse() { return new WebSocketHeartBeatResponse(); } /** * 引擎中定义默认的心跳包响应对象,由系统自动发出,外部对象不会使用。 * @author 时克英 * */ private class WebSocketHeartBeatResponse extends JsonResponse{ /** * */ private static final long serialVersionUID = 775725794320035005L; @Override protected void translateProperties(Map result) { // nothing } @Override public String getProtocolNum() { return Constants.PROTOCOL_HEART_BEAT; } @Override public String getDelimiter() { return StringUtils.EMPTY_STRING; } } @JsonIgnore @Override public String getAuthenticateInfo(Request request) throws AuthenticateException { if(this.logger.isDebugEnabled()){ try { logger.debug("需要认证请求:{}", JsonUtils.objectToJsonString(request)); } catch (Exception e) { e.printStackTrace(); } } String clientId = request.getName(); if(StringUtils.isEmpty(clientId)){ throw new AuthenticateException("请求信息中不存在设备ID号,无法认证"); } if(!isPermitNotRegisterConnect() && !this.isRegistered(clientId)){ throw new AuthenticateException("设备未在列表中注册,无法认证。clientId = " + clientId); } return clientId; } }