| | |
| | | package com.whyc.webSocket; |
| | | |
| | | import com.google.gson.reflect.TypeToken; |
| | | import com.whyc.dto.CarCamera; |
| | | import com.whyc.dto.Login; |
| | | import com.whyc.factory.ThreadPoolExecutorFactory; |
| | | import com.whyc.pojo.Response; |
| | | import com.whyc.service.AirconditionerStateService; |
| | | import com.whyc.service.CarCameraService; |
| | | import com.whyc.util.ActionUtil; |
| | |
| | | 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) |
| | |
| | | |
| | | @OnMessage |
| | | public void onMessage(Session session, String message){ |
| | | Login login= ActionUtil.getGson().fromJson(message,Login.class); |
| | | List<Login> list= ActionUtil.getGson().fromJson(message,new TypeToken<List<Login>>(){}.getType()); |
| | | thread = new Thread("Thread_airSocket") { |
| | | @Override |
| | | public void run() { |
| | | while (runFlag && !isInterrupted()) { |
| | | try { |
| | | Map<String, Object> map = new HashMap<>(); |
| | | while (!currentThread().isInterrupted()) { |
| | | Thread thread = currentThread(); |
| | | threadFlagMap.put(thread.getId(), true); |
| | | try { |
| | | if (session.isOpen()) { |
| | | //推送信息 |
| | | synchronized (session) { |
| | | session.getBasicRemote().sendObject(service.getCarCamera(login)); |
| | | 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(); |
| | | }); |
| | | } |
| | | threadFlagMap.put(thread.getId(), false); |
| | | latch.await(10, TimeUnit.MINUTES); |
| | | session.getBasicRemote().sendObject(new Response().set(1, map)); |
| | | sleep(5000); |
| | | } |
| | | sleep(executeTime); |
| | | //} catch (IOException | InterruptedException | EncodeException e) { |
| | | } catch (Exception e) { |
| | | interrupt(); |
| | | } |
| | | this.interrupt(); |
| | | } |
| | | } |
| | | }; |
| | | thread.start(); |
| | | threadFlagMap.put(thread.getId(), true); |
| | | //停止老的socket线程 |
| | | Thread threadBefore = threadMap.get(session.getId()); |
| | | if (threadBefore != null && threadBefore.isAlive()) { |
| | | while (threadFlagMap.get(threadBefore.getId())) { |
| | | } |
| | | threadBefore.interrupt(); |
| | | } |
| | | //将线程存储,便于调用定位 |
| | | threadMap.put(session.getId(), this.thread); |
| | | this.thread = thread; |
| | | } |
| | | |
| | | @OnClose |