| | |
| | | package com.whyc.ws; |
| | | |
| | | import com.whyc.service.DeviceService; |
| | | import io.swagger.annotations.Api; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.websocket.*; |
| | | import javax.websocket.server.PathParam; |
| | | import javax.websocket.server.ServerEndpoint; |
| | | import java.io.IOException; |
| | | |
| | | @ServerEndpoint(value = "/device", encoders = WebSocketEncoder.class) |
| | | @ServerEndpoint(value = "/device/{deviceId}", encoders = WebSocketEncoder.class) |
| | | @Component |
| | | @Api(tags = "设备ws") |
| | | @Slf4j |
| | |
| | | |
| | | private volatile Thread thread; |
| | | |
| | | //private Integer deviceId; |
| | | |
| | | private static DeviceService service; |
| | | |
| | | @Autowired |
| | | public void setService(DeviceService service) { |
| | | this.service = service; |
| | | } |
| | | |
| | | @OnOpen |
| | | public void onOpen(Session session) { |
| | | public void onOpen(Session session, @PathParam("deviceId") Integer deviceId) { |
| | | log.warn("socket会话开启了:{}",session); |
| | | this.session = session; |
| | | //this.deviceId = deviceId; |
| | | if(session!=null) { |
| | | thread = new Thread("Thread_device") { |
| | | public void run() { |
| | | while (!thread.isInterrupted()) { |
| | | try { |
| | | if (session.isOpen()) { |
| | | session.getBasicRemote().sendObject(service.getStatus(deviceId)); |
| | | } |
| | | sleep(1000); |
| | | } catch (IOException | InterruptedException | EncodeException e) { |
| | | interrupt(); |
| | | } |
| | | } |
| | | } |
| | | }; |
| | | thread.start(); |
| | | } |
| | | } |
| | | |
| | | @OnMessage |
| | |
| | | while (!thread.isInterrupted()) { |
| | | try { |
| | | if (session.isOpen()) { |
| | | //session.getBasicRemote().sendObject("1"); |
| | | session.getBasicRemote().sendObject(new Object()); |
| | | //session.getBasicRemote().sendObject(service.getStatus()); |
| | | session.getBasicRemote().sendObject(null); |
| | | } |
| | | sleep(1000); |
| | | } catch (IOException | InterruptedException | EncodeException e) { |