简体   繁体   English

Java Spring 启动 websocket 与 JS 通信

[英]Java Spring boot websocket communication with JS

I have the following WebSocketConfig in my Spring boot app:我的 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");
    }
}

and this code in my controller:和我的控制器中的这段代码:

@Autowired
    private SimpMessagingTemplate template;

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

I'm trying to read those messages using my javascript application this way:我正在尝试以这种方式使用我的 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');
    });

Although I'm subscribed to /updateService, I can't get any message.虽然我订阅了 /updateService,但我无法收到任何消息。

Console log shows all fine:控制台日志显示一切正常:

在此处输入图片说明

Although in my Spring boot app I see scheduled in my console, I get no message in my client.尽管在我的 Spring Boot 应用scheduled中,我在控制台中看到已scheduled ,但我的客户端中没有收到任何消息。

Any ideas what could have gone wrong?任何想法可能出了什么问题?

Sorry I don't have enough reputation to leave a comment to your post, so I will reply.抱歉,我没有足够的声誉来对您的帖子发表评论,所以我会回复。

  1. you can enable logging in application.properties to see what actually happens with WS connection.您可以在application.properties启用登录以查看 WS 连接实际发生的情况。

     logging.level.org.springframework.messaging=trace logging.level.org.springframework.web.socket=trace
  2. connected to server undefined doesn't mean that something is wrong. connected to server undefined并不意味着出现问题。 This line appears every time.这条线每次都会出现。

  3. I've tried to reproduce your issue and it works fine on my side.我试图重现您的问题,它在我这边工作正常。 Do you have additional routing or security configuration (I've noticed http s and a custom port)?你有额外的路由或安全配置(我已经注意到HTTP S和一个自定义的端口)? Here is the code in case you need to check:这是您需要检查的代码:

Controller:控制器:

@Controller
public class SomeController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

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

Main app & Websocket config (don't forget @EnableWebSocketMessageBroker ):主应用程序和 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");
    }
}

And this is JS code:这是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>

I know the question is old, but perhaps my answer will help someone else.我知道这个问题很老,但也许我的回答会帮助别人。

I had a similar issue.我有一个类似的问题。 My task was to keep user updated regarding some ongoing process, so my application had to send every 5 seconds a message.我的任务是让用户了解一些正在进行的过程,所以我的应用程序必须每 5 秒发送一次消息。

The front-end Vue.js application is served separately on node.前端 Vue.js 应用程序在 node 上单独提供服务。 Inside component which had to monitor the task I have added:必须监视我添加的任务的内部组件:

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

On server side (Spring Application written in Kotlin) I have added Configuration class在服务器端(用 Kotlin 编写的 Spring 应用程序)我添加了 Configuration 类

@Configuration
class WebSocketConfig : WebSocketMessageBrokerConfigurer {

    override fun registerStompEndpoints(registry: StompEndpointRegistry) {

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

As you may I see, I DO NOT override configureMessageBroker method如您所见,我不会覆盖configureMessageBroker方法

In main class I enable web-sockets and scheduling在主课中,我启用了网络套接字和调度

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

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

And here is component that sends messages to socket :这是向 socket 发送消息的组件:

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

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

Please note, that I have to write full destination as a parameter when calling method convertAndSend .请注意,在调用方法convertAndSend时,我必须写完整的目的地作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM