stomp链接成功后给客户端发送消息
时间: 2024-02-01 21:13:01 浏览: 23
在Stomp协议中,客户端需要订阅一个或多个主题(topic)来接收消息。所以在发送消息之前,需要先让客户端订阅一个主题。
以下是一个Java Spring Boot应用程序中使用Stomp发送消息的示例代码:
```java
@Controller
public class MyController {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@MessageMapping("/send-message")
public void sendMessage(String message) {
messagingTemplate.convertAndSend("/topic/my-topic", message);
}
}
```
在上面的代码中,我们注入了一个SimpMessagingTemplate类的实例,该类是Spring Framework提供的一个方便的消息发送器。在sendMessage方法中,我们使用messagingTemplate实例将消息发送到“/topic/my-topic”主题中。
现在,客户端需要订阅“/topic/my-topic”主题来接收消息。以下是一个JavaScript客户端代码示例:
```javascript
var socket = new SockJS('/my-websocket-endpoint');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
stompClient.subscribe('/topic/my-topic', function(message) {
console.log('Received message: ' + message.body);
});
});
function sendMessage() {
var message = document.getElementById('message-input').value;
stompClient.send('/app/send-message', {}, message);
}
```
在这个例子中,我们使用了SockJS和Stomp.js库来与Stomp服务器进行通信。在连接成功后,我们订阅了“/topic/my-topic”主题,并在接收到消息时打印出来。在sendMessage函数中,我们从文本框中获取消息并使用stompClient实例将其发送到“/app/send-message”端点。这个端点会触发MyController类中的sendMessage方法,然后该方法会将消息发送到“/topic/my-topic”主题中,最终被所有订阅该主题的客户端接收到。