1、pom引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、创建SockJsClient类,调用回调类MyHandler,定时任务开启,注入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、处理类
@Component
public class MyHandler implements WebSocketHandler {
@Resource
private TransferStationService transferStationService;
//发送指令
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
System.out.println("connection is established!");
JSONObject jsonObject = new JSONObject();
webSocketSession.sendMessage(new TextMessage(jsonObject.toString()));
}
//接受返回数据
@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 {
}
//链接时首先调用
@Override
public boolean supportsPartialMessages() {
return false;
}
}
网友评论