簡體   English   中英

Java Spring 啟動 websocket 與 JS 通信

[英]Java Spring boot websocket communication with JS

我的 Spring boot 應用程序中有以下 WebSocketConfig:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");
    }
}

和我的控制器中的這段代碼:

@Autowired
    private SimpMessagingTemplate template;

    @Scheduled(fixedRate = 5000)
    public void getMessage() {
        System.out.println("scheduled");
        this.template.convertAndSend("/topic/updateService", "Hello");
    }

我正在嘗試以這種方式使用我的 javascript 應用程序讀取這些消息:

let socket = new SockJS(`https://localhost:8443/ws`);
    let stompClient = Stomp.over(socket);

    stompClient.connect({}, () => {
      stompClient.subscribe('/topic/updateService', (data) => {
        console.log("New message!");
        console.log(data);
      });
    }, () => {
      console.log('failed');
    });

雖然我訂閱了 /updateService,但我無法收到任何消息。

控制台日志顯示一切正常:

在此處輸入圖片說明

盡管在我的 Spring Boot 應用scheduled中,我在控制台中看到已scheduled ,但我的客戶端中沒有收到任何消息。

任何想法可能出了什么問題?

抱歉,我沒有足夠的聲譽來對您的帖子發表評論,所以我會回復。

  1. 您可以在application.properties啟用登錄以查看 WS 連接實際發生的情況。

     logging.level.org.springframework.messaging=trace logging.level.org.springframework.web.socket=trace
  2. connected to server undefined並不意味着出現問題。 這條線每次都會出現。

  3. 我試圖重現您的問題,它在我這邊工作正常。 你有額外的路由或安全配置(我已經注意到HTTP S和一個自定義的端口)? 這是您需要檢查的代碼:

控制器:

@Controller
public class SomeController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Scheduled(fixedDelay = 1000)
    private void send() {
        simpMessagingTemplate.convertAndSend("/topic/updateService", "Hello");
    }
}

主應用程序和 Websocket 配置(不要忘記@EnableWebSocketMessageBroker ):

@SpringBootApplication
@EnableScheduling
@EnableWebSocketMessageBroker
public class Main extends AbstractWebSocketMessageBrokerConfigurer {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");
    }
}

這是JS代碼:

<script type="text/javascript">
        var stompClient = null;

        function connect() {
            var socket = new SockJS("http://localhost:8443/ws");
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function () {
                stompClient.subscribe('/topic/updateService', function (data) {
                    console.log(data);
                });
            });
        }

        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            console.log("Disconnected");
        }

</script>

我知道這個問題很老,但也許我的回答會幫助別人。

我有一個類似的問題。 我的任務是讓用戶了解一些正在進行的過程,所以我的應用程序必須每 5 秒發送一次消息。

前端 Vue.js 應用程序在 node 上單獨提供服務。 必須監視我添加的任務的內部組件:

<script>    
import SockJS from 'sockjs-client'
const Stomp = require('stompjs')
const socket = new SockJS('http://localhost:8088/monitor/activity',{transports: ['websocket'] })

// Usual Vue-js stuff
methods: {
  subscribe (frame) {
    console.log('Subscribed to: ' + frame)
    this.stompClient.subscribe('/web-socket/activity', (payload) => {
      console.log('Successfully handled message :' + payload)
    })
  },
  connect () {
    this.stompClient = Stomp.over(socket)
    this.stompClient.connect({}, this.subscribe)
  }
},
mounted() {
  this.connect
}
</script>

在服務器端(用 Kotlin 編寫的 Spring 應用程序)我添加了 Configuration 類

@Configuration
class WebSocketConfig : WebSocketMessageBrokerConfigurer {

    override fun registerStompEndpoints(registry: StompEndpointRegistry) {

        registry.addEndpoint("/monitor/activity")
                .setAllowedOrigins("*")
                .withSockJS()
    }
}

如您所見,我不會覆蓋configureMessageBroker方法

在主課中,我啟用了網絡套接字和調度

@SpringBootApplication
@EnableScheduling
@EnableWebSocketMessageBroker
@EnableWebSocket
public class SpringBootVuejsApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootVuejsApplication.class, args);
    }
}

這是向 socket 發送消息的組件:

@Component
class LoanScheduledCron
@Autowired constructor(
        private val messagingTemplate: SimpMessagingTemplate
) {

    @Scheduled(fixedDelay = 5000)
    fun getSchedulersActivity () {
        messagingTemplate.convertAndSend("/web-socket/activity", "Still active")
    }
}

請注意,在調用方法convertAndSend時,我必須寫完整的目的地作為參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM