1、pom引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2髓帽、創(chuàng)建SockJsClient類(lèi),調(diào)用回調(diào)類(lèi)MyHandler盼樟,定時(shí)任務(wù)開(kāi)啟氢卡,注入url
public class LightMWServiceImpl implements IbmsLightService {
@Resource
private MyHandler myHandler;
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void syncLightItemStatusTimeTask(){
this.initSocket();
}
public void initSocket(){
List<Transport> transports = new ArrayList<>(1);
transports.add(new RestTemplateXhrTransport());
SockJsClient sockJsClient = new SockJsClient(transports);
sockJsClient.doHandshake(myHandler, url);
}
}
3、處理類(lèi)
@Component
public class MyHandler implements WebSocketHandler {
@Resource
private TransferStationService transferStationService;
//發(fā)送指令
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
System.out.println("connection is established!");
JSONObject jsonObject = new JSONObject();
webSocketSession.sendMessage(new TextMessage(jsonObject.toString()));
}
//接受返回?cái)?shù)據(jù)
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
System.out.println(webSocketMessage);
}
@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
}
//鏈接時(shí)首先調(diào)用
@Override
public boolean supportsPartialMessages() {
return false;
}
}