package com.whyc.webSocket; import com.google.gson.reflect.TypeToken; import com.whyc.dto.Login; import com.whyc.factory.ThreadPoolExecutorFactory; import com.whyc.pojo.Response; import com.whyc.service.CarCameraService; import com.whyc.util.ActionUtil; import com.whyc.util.WebSocketEncoderUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @Component @ServerEndpoint(value = "/carCameraSocket",encoders = WebSocketEncoderUtil.class) public class CarCameraWebSocket { private volatile Thread thread; private static final int executeTime = 5000; private volatile boolean runFlag=true; private volatile Map threadMap = new HashMap<>(); private volatile Map threadFlagMap = new HashMap<>(); private static CarCameraService service; private Session session; @Autowired public void setService(CarCameraService service){ CarCameraWebSocket.service = service; } @OnOpen public void onOpen(Session session){ this.session=session; } @OnMessage public void onMessage(Session session, String message){ List list= ActionUtil.getGson().fromJson(message,new TypeToken>(){}.getType()); thread = new Thread("Thread_airSocket") { @Override public void run() { try { Map map = new HashMap<>(); while (!currentThread().isInterrupted()) { Thread thread = currentThread(); threadFlagMap.put(thread.getId(), true); ThreadPoolExecutor poolExecutor = ThreadPoolExecutorFactory.getPoolExecutor(); CountDownLatch latch = new CountDownLatch(list.size()); for (Login login:list) { poolExecutor.execute(() -> { Response res=service.getCarCamera(login); map.put(login.getIp(),res); latch.countDown(); }); } latch.await(10, TimeUnit.MINUTES); session.getBasicRemote().sendObject(new Response().set(1, map)); sleep(5000); } } catch (Exception e) { this.interrupt(); } } }; thread.start(); this.thread = thread; } @OnClose public void onClose(CloseReason closeReason){ System.err.println("closeReason = " + closeReason); runFlag = false; if (thread != null && thread.isAlive()) { thread.interrupt(); } threadMap.remove(session.getId()); } @OnError public void onError(Throwable error) { error.printStackTrace(); if (thread != null && thread.isAlive()) { thread.interrupt(); } threadMap.remove(session.getId()); } }