在 Svelte 中订阅 Websockets 主题

Subscribing to a Websockets topic in Svelte

以前,我在客户端使用 Stomp for Websockets,订阅特定主题。例如:

    const url = "ws://localhost:8080";

    //const socket = new SockJS(url);
    const socket = new WebSocket(url);
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function () {
        stompClient.subscribe('/topic/someTopic.*', function (output) {
            //parse the message
        });

        setConnected(true);
    }, function (err) {
        alert('Error: ' + err);
    });

在 Svelte 和 Node Websockets 中,我看到了如下连接方式:

let socket
onMount(() => {
  socket = new WebSocket("ws://localhost:8000/chat")
  socket.addEventListener("open", ()=> {
    console.log("Opened")
  })
})

但是,我如何订阅特定主题?是否有替代方案可以提供此功能?

您可以在 svelte 组件中执行您想要的每个 javascript,只需确保 DOM 已通过在 onMount:

中调用它来呈现
<script>
  import { onMount } from 'svelte';
  const URL = "ws://localhost:8080";
  
  const subscribeToTopic = () => {
    //const socket = new SockJS(URL);
    const socket = new WebSocket(URL);
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function () {
        stompClient.subscribe('/topic/someTopic.*', function (output) {
            //parse the message
        });

        setConnected(true);
    }, function (err) {
        alert('Error: ' + err);
    });
  }

  onMount(() => {
    subscribeToTopic();
  });

</script>