| | |
| | | import javax.websocket.*; |
| | | import javax.websocket.server.ServerEndpoint; |
| | | import java.io.IOException; |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * 账号重复登录检查 |
| | |
| | | public void onOpen(Session session, EndpointConfig config){ |
| | | this.session = session; |
| | | HttpSession httpSession = (HttpSession) config.getUserProperties().get("httpSession"); |
| | | Thread thread = new Thread() { |
| | | @Override |
| | | public void run() { |
| | | try { |
| | | while (!currentThread().isInterrupted()) { |
| | | Response response = loginService.checkUserWebSocket(httpSession); |
| | | session.getBasicRemote().sendObject(response); |
| | | sleep(4000); |
| | | } |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } catch (EncodeException e) { |
| | | e.printStackTrace(); |
| | | } catch (InterruptedException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | if(httpSession == null){ |
| | | Map<String, Response> res = new HashMap<>(); |
| | | Response resp1 = new Response().set(1, false, "登录信息失效,重新登录"); |
| | | res.put("checkLogin", resp1); |
| | | try { |
| | | session.getBasicRemote().sendObject(new Response().set(1,res)); |
| | | } catch (IOException | EncodeException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | }; |
| | | thread.start(); |
| | | this.thread = thread; |
| | | |
| | | }else { |
| | | Thread thread = new Thread() { |
| | | @Override |
| | | public void run() { |
| | | try { |
| | | Map<String, Response> res = new HashMap<>(); |
| | | Response sessionRes = new Response().set(1, httpSession.getId()); |
| | | while (!currentThread().isInterrupted()) { |
| | | Response response = loginService.checkUserWebSocket(httpSession); |
| | | res.put("checkLogin", response); |
| | | res.put("session", sessionRes); |
| | | session.getBasicRemote().sendObject(new Response().set(1, res)); |
| | | if (response.getData() instanceof Boolean) { |
| | | if(response.getData().equals(false)) { |
| | | this.interrupt(); |
| | | } |
| | | } |
| | | sleep(4000); |
| | | } |
| | | } catch (Exception e) { |
| | | this.interrupt(); |
| | | } |
| | | } |
| | | }; |
| | | thread.start(); |
| | | this.thread = thread; |
| | | } |
| | | } |
| | | |
| | | @OnClose |
| | | public void onOpen(Session session){ |
| | | public void onClose(CloseReason closeReason) throws IOException { |
| | | System.err.println("closeReason = " + closeReason); |
| | | if(session.isOpen()){ |
| | | session.close(); |
| | | } |
| | | } |
| | | |
| | | @OnError |
| | | public void onError(Throwable error) throws IOException { |
| | | error.printStackTrace(); |
| | | thread.isInterrupted(); |
| | | if(session.isOpen()){ |
| | | session.close(); |
| | | } |
| | | } |
| | | |
| | | } |