Spring:向websocket客户端发送消息
我正在使用Spring Boot,RabbitMQ和WebSocket作为POC构建网络聊天,但最后一点是:WebSockets
我希望我的ws客户端连接到特定的端点,例如/room/{id}
当有新消息到达时,我希望服务器将响应发送给客户端,但是我搜索了类似内容但未找到。
目前,当消息到达时,我使用RabbitMQ对其进行处理,例如
container.setMessageListener(new MessageListenerAdapter(){ @Override
public void onMessage(org.springframework.amqp.core.Message message, Channel channel) throws Exception {
log.info(message);
log.info("Got: "+ new String(message.getBody()));
}
});
我想要的是,而不是登录它,我想将其发送给客户端,例如: websocketManager.sendMessage(new
String(message.getBody()))
回答:
好的,我想我明白了,对于需要它的每个人,这是答案:
首先,您需要将WS依赖项添加到pom.xml中
<dependency> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
创建一个WS端点
@Configuration@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// the endpoint for websocket connections
registry.addEndpoint("/stomp").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/");
// use the /app prefix for others
config.setApplicationDestinationPrefixes("/app");
}
}
注意:我使用的是STOMP,因此客户端应该这样连接
<script type="text/javascript"> $(document).ready(function() {
var messageList = $("#messages");
// defined a connection to a new socket endpoint
var socket = new SockJS('/stomp');
var stompClient = Stomp.over(socket);
stompClient.connect({ }, function(frame) {
// subscribe to the /topic/message endpoint
stompClient.subscribe("/room.2", function(data) {
var message = data.body;
messageList.append("<li>" + message + "</li>");
});
});
});
</script>
然后,您可以简单地将ws Messenger连接到组件上
@Autowiredprivate SimpMessagingTemplate webSocket;
并发送消息与
webSocket.convertAndSend(channel, new String(message.getBody()));
以上是 Spring:向websocket客户端发送消息 的全部内容, 来源链接: utcz.com/qa/413524.html