Java Spring 启动websocket与JS通信
Java Spring boot websocket communication with JS
我的 Spring 启动应用程序中有以下 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 启动应用程序中,我在我的控制台中看到 scheduled
,但我在我的客户端中没有收到任何消息。
知道哪里出了问题吗?
抱歉,我没有足够的声誉给您的 post 发表评论,所以我会回复。
您可以启用登录 application.properties
以查看 WS 连接的实际情况。
logging.level.org.springframework.messaging=trace
logging.level.org.springframework.web.socket=trace
connected to server undefined
并不代表有问题。每次都会出现这条线。
我已尝试重现您的问题,我这边效果很好。您是否有额外的路由或安全配置(我注意到 https 和自定义端口)?这是代码,以备您需要检查时使用:
控制器:
@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 应用程序在节点上单独提供服务。必须监视我添加的任务的内部组件:
<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>
在服务器端(Spring 用 Kotlin 编写的应用程序)我添加了配置 class
@Configuration
class WebSocketConfig : WebSocketMessageBrokerConfigurer {
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/monitor/activity")
.setAllowedOrigins("*")
.withSockJS()
}
}
如你所见,我不要覆盖configureMessageBroker
方法
在主程序中 class 我启用网络套接字和调度
@SpringBootApplication
@EnableScheduling
@EnableWebSocketMessageBroker
@EnableWebSocket
public class SpringBootVuejsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootVuejsApplication.class, args);
}
}
这是向套接字发送消息的组件:
@Component
class LoanScheduledCron
@Autowired constructor(
private val messagingTemplate: SimpMessagingTemplate
) {
@Scheduled(fixedDelay = 5000)
fun getSchedulersActivity () {
messagingTemplate.convertAndSend("/web-socket/activity", "Still active")
}
}
请注意,在调用方法 convertAndSend
时,我必须将完整的目标写为参数。
我的 Spring 启动应用程序中有以下 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 启动应用程序中,我在我的控制台中看到 scheduled
,但我在我的客户端中没有收到任何消息。
知道哪里出了问题吗?
抱歉,我没有足够的声誉给您的 post 发表评论,所以我会回复。
您可以启用登录
application.properties
以查看 WS 连接的实际情况。logging.level.org.springframework.messaging=trace logging.level.org.springframework.web.socket=trace
connected to server undefined
并不代表有问题。每次都会出现这条线。我已尝试重现您的问题,我这边效果很好。您是否有额外的路由或安全配置(我注意到 https 和自定义端口)?这是代码,以备您需要检查时使用:
控制器:
@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 应用程序在节点上单独提供服务。必须监视我添加的任务的内部组件:
<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>
在服务器端(Spring 用 Kotlin 编写的应用程序)我添加了配置 class
@Configuration
class WebSocketConfig : WebSocketMessageBrokerConfigurer {
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/monitor/activity")
.setAllowedOrigins("*")
.withSockJS()
}
}
如你所见,我不要覆盖configureMessageBroker
方法
在主程序中 class 我启用网络套接字和调度
@SpringBootApplication
@EnableScheduling
@EnableWebSocketMessageBroker
@EnableWebSocket
public class SpringBootVuejsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootVuejsApplication.class, args);
}
}
这是向套接字发送消息的组件:
@Component
class LoanScheduledCron
@Autowired constructor(
private val messagingTemplate: SimpMessagingTemplate
) {
@Scheduled(fixedDelay = 5000)
fun getSchedulersActivity () {
messagingTemplate.convertAndSend("/web-socket/activity", "Still active")
}
}
请注意,在调用方法 convertAndSend
时,我必须将完整的目标写为参数。