New file |
| | |
| | | package com.whyc.webSocket; |
| | | |
| | | import com.whyc.config.WebSocketConfig; |
| | | import com.whyc.dto.Response; |
| | | import com.whyc.factory.ThreadPoolExecutorFactory; |
| | | import com.whyc.pojo.plus_user.UserInf; |
| | | import com.whyc.service.HomeService; |
| | | import com.whyc.service.StationInfService; |
| | | 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; |
| | | import java.util.concurrent.CountDownLatch; |
| | | import java.util.concurrent.ThreadPoolExecutor; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * 左侧列表推送 |
| | | */ |
| | | |
| | | @Component |
| | | @ServerEndpoint(value = "/leftStation",encoders = WebSocketEncoder.class,configurator = WebSocketConfig.class) |
| | | public class StationInfSocket { |
| | | |
| | | private Session session; |
| | | |
| | | private Thread thread; |
| | | |
| | | private static StationInfService stationService; |
| | | |
| | | @Autowired |
| | | public void setStationInfService(StationInfService stationService) { |
| | | StationInfSocket.stationService = stationService; |
| | | } |
| | | |
| | | |
| | | |
| | | @OnOpen |
| | | public void onOpen(Session session, EndpointConfig config) { |
| | | this.session = session; |
| | | HttpSession httpSession = (HttpSession) config.getUserProperties().get("httpSession"); |
| | | UserInf user = (UserInf) httpSession.getAttribute("user"); |
| | | final int userId = user.getUid(); |
| | | //final int userId = 10001; |
| | | |
| | | Thread thread = new Thread("Thread_HomeSocket") { |
| | | @Override |
| | | public void run() { |
| | | try { |
| | | |
| | | while (!currentThread().isInterrupted()) { |
| | | while (!currentThread().isInterrupted()) { |
| | | Response res = stationService.getLeftStation(userId); |
| | | session.getBasicRemote().sendObject(res); |
| | | sleep(5000); |
| | | } |
| | | } |
| | | } catch (Exception e) { |
| | | this.interrupt(); |
| | | } |
| | | } |
| | | }; |
| | | thread.start(); |
| | | this.thread = thread; |
| | | } |
| | | |
| | | @OnClose |
| | | 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(); |
| | | } |
| | | } |
| | | } |