package com.whyc.webSocket;
|
|
import com.whyc.config.WebSocketConfig;
|
import com.whyc.dto.Response;
|
import com.whyc.service.LoginService;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.stereotype.Component;
|
|
import javax.servlet.http.HttpSession;
|
import javax.websocket.*;
|
import javax.websocket.server.ServerEndpoint;
|
import java.io.IOException;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
/**
|
* 账号重复登录检查
|
*/
|
@Component
|
@ServerEndpoint(value = "/loginCheck",encoders = WebSocketEncoder.class,configurator = WebSocketConfig.class)
|
public class LoginCheckSocket {
|
|
private Session session;
|
|
private Thread thread;
|
private static LoginService loginService;
|
|
@Autowired
|
public void setLoginService(LoginService loginService) {
|
LoginCheckSocket.loginService = loginService;
|
}
|
|
@OnOpen
|
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 {
|
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));
|
sleep(4000);
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
} catch (EncodeException e) {
|
e.printStackTrace();
|
} catch (InterruptedException e) {
|
e.printStackTrace();
|
}catch (Exception e){
|
e.printStackTrace();
|
}
|
}
|
};
|
thread.start();
|
this.thread = thread;
|
|
}
|
|
@OnClose
|
public void onClose(CloseReason closeReason){
|
System.err.println("closeReason = " + closeReason);
|
thread.isInterrupted();
|
}
|
|
@OnError
|
public void onError(Throwable error){
|
error.printStackTrace();
|
thread.isInterrupted();
|
}
|
|
}
|