[英]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
,但我的客户端中没有收到任何消息。
任何想法可能出了什么问题?
抱歉,我没有足够的声誉来对您的帖子发表评论,所以我会回复。
您可以在application.properties
启用登录以查看 WS 连接实际发生的情况。
logging.level.org.springframework.messaging=trace logging.level.org.springframework.web.socket=trace
connected to server undefined
并不意味着出现问题。 这条线每次都会出现。
我试图重现您的问题,它在我这边工作正常。 你有额外的路由或安全配置(我已经注意到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.