gpt4 book ai didi

java - Spring 和 Java 中的 Websocket

转载 作者:行者123 更新时间:2023-12-01 13:32:08 25 4
gpt4 key购买 nike

对于我在 Spring 中构建的项目,我想实现 websocket。我找到了 STOMP 形式的解决方案,但我找不到向单个用户发送 websocket 消息的方法,只能找到向所有客户端进行完整广播的方法。有哪些好的替代方案可以轻松插入 Spring 并可以用来发送和接收消息?我在 Spring 中有一个自滚动用户系统(而不是使用 Spring Security),我想将其与此结合起来。

编辑:我想指出的是,我想要一个可以优雅地降级为其他通信协议(protocol)的解决方案,就像 socket.io 所做的那样。

最佳答案

要将 Spring 与 websocket 结合使用,请查看新的 Spring Websocket support in Spring 4 ,这是一个presentation关于它。

根据文档,Spring支持单用户连接,以及广播:

Spring Framework allows @Controller classes to have both HTTP request handling and WebSocket message handling methods. Furthermore, a Spring MVC request handling method, or any application method for that matter, can easily broadcast a message to all interested WebSocket clients or to a specific user.

这是一个广播示例,您已经可以执行此操作:

@Controller
public class GreetingController {

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(3000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}

}

根据文档,不广播而只回复调用客户的方法是省略@SendTo注释:

By default the return value from an @SubscribeMapping method is sent as a message directly back to the connected client and does not pass through the broker. This is useful for implementing request-reply message interactions;

关于java - Spring 和 Java 中的 Websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21512706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com