美文网首页
java 接受sockjs服务数据

java 接受sockjs服务数据

作者: 周六不算加班 | 来源:发表于2021-06-11 17:29 被阅读0次

    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;
    }
    

    }

    相关文章

      网友评论

          本文标题:java 接受sockjs服务数据

          本文链接:https://www.haomeiwen.com/subject/gkeveltx.html