1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| @ServerEndpoint(value = "/ws/{role}/{token}", configurator = EndpointConf.class) @Component @Slf4j public class WsController {
private static final String PARAM_TOKEN = "token"; private static final String PARAM_ROLE = "role"; private static final Set<String> ROLE_SET = new HashSet<>( Arrays.asList(AccountType.DRIVER.name().toLowerCase(), AccountType.PASSENGER.name().toLowerCase()) );
@Autowired private WsService wsService;
@OnOpen public void onOpen(@PathParam(PARAM_ROLE) String role, @PathParam(PARAM_TOKEN) String token, Session session) throws IOException { if (!ROLE_SET.contains(role)) { log.warn("token:{} login role error, role:{}", token, role); wsService.sendMessage(session, wsService.authFailMsg()); session.close(); return; }
int userId = wsService.getUserIdByToken(role, token); if (userId == -1) { log.warn("token:{} login error, you are offline", token); wsService.sessionMap.remove(token); wsService.sendMessage(session, wsService.authFailMsg()); session.close(); return; } log.info("【{}】, token : {} open websocket connect", wsService.showInfoAboutToken(token), token);
Session oldSession = wsService.sessionMap.get(token); if (oldSession != null) { wsService.sessionMap.remove(token); wsService.sendMessage(oldSession, wsService.duplicateLoginMsg()); oldSession.close(); } wsService.sessionMap.put(token, session); }
@OnClose public void onClose(@PathParam(PARAM_ROLE) String role, @PathParam(PARAM_TOKEN) String token, Session session) { log.info("close connection. 【{}】, token: {}", wsService.showInfoAboutToken(token), token); wsService.sessionMap.remove(token); wsService.sendMessage(session, wsService.authFailMsg()); }
@OnError public void onError(@PathParam(PARAM_ROLE) String role, @PathParam(PARAM_TOKEN) String token, Session session, Throwable error) { log.error("【{}】, token : {}, sessionId: {}, websocket error: {}", wsService.showInfoAboutToken(token), token, session.getId(), error); }
@OnMessage public void onMessage(@PathParam(PARAM_ROLE) String role, @PathParam(PARAM_TOKEN) String token, String message, Session session) throws IOException { log.info("receive from 【{}】, token : {}, message: {}",wsService.showInfoAboutToken(token), token, message); if (!ROLE_SET.contains(role)) { wsService.sendMessage(session, wsService.authFailMsg()); session.close(); } if(role.equals(AccountType.DRIVER.name().toLowerCase())){ wsService.updateHeartBeat(token); } wsService.actionHandle(session, message); } }
|