标签: spring-websocket

带 websocket 和邮递员的 Spring Boot

我已经根据教程创建了测试项目

@Configuration
@EnableWebSocketMessageBroker
public class WSConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat");
        registry.addEndpoint("/chat").withSockJS();
    }

@Controller
public class WSController {

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public String send(String message) throws Exception {
        return "test";
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在努力与邮递员联系,我尝试了不同的网址:

  • ws://本地主机:8080

  • ws://localhost:8080/应用程序

  • ws://localhost:8080/app/chat

每次我单击连接按钮时,都会收到 404 作为响应我做错了什么?(我是 websocket 新手)

spring-boot spring-websocket postman

5
推荐指数
1
解决办法
9102
查看次数

如何修复 Spring Boot WebSocket 应用程序中的“Access-Control-Allow-Origin”问题?

全部。我是 Spring Boot 和 Websocket 的新手。这是我的第一个集成 React 和 Spring Boot 项目,我目前正在使用 WebSocket 构建一个带有后端的聊天应用程序。

如前所述,我的前端是在 React (localhost:3000) 中构建的,但是当尝试调用后端/聊天应用程序时,我收到错误:

Access to XMLHttpRequest at 'http://localhost:9090/ws/info?t=1652731448126' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Run Code Online (Sandbox Code Playgroud)

我尝试查找一些可能的解决方案,例如使用@CrossOrigin(origins = "https://localhost:3000")and@CrossOrigin(origins = "http://localhost:3000")但这并没有改变任何东西。我也尝试过(@CrossOrigin(origins = "*") …

cors reactjs spring-boot spring-websocket

5
推荐指数
1
解决办法
6480
查看次数

Spring Boot WebSocket Broker 不发送 CONNECTED 帧

不幸的是,我最近在生产环境中遇到了一个问题,当我的 Spring Boot 服务器没有发送 CONNECT 帧(即 CONNECTED 帧)的响应时。这种情况一开始偶尔发生,但后来浏览器发送的所有 CONNECT 请求都没有得到回复。

控制台日志

在控制台上我能够看到以下日志 在此输入图像描述

经过一番调查,我发现 inboundChannel 队列当时持有很多请求。我相信这就是原因。

2022-06-01 18:22:59,943 INFO  Thread-id-74- springframework.web.socket.config.WebSocketMessageBrokerStats: WebSocketSession[130 current WS(129)-HttpStream(1)-HttpPoll(0), 225 total, 0 closed abnormally (0 connect failure, 0 send limit, 2 transport error)], stompSubProtocol[processed CONNECT(220)-CONNECTED(132)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 2, active threads = 2, queued tasks = 10774, completed tasks = 31806], outboundChannel[pool size = 2, active threads = 0, queued tasks = 0, completed tasks = 570895], sockJsScheduler[pool size = 1, active threads = 1, queued …
Run Code Online (Sandbox Code Playgroud)

java spring stomp spring-boot spring-websocket

5
推荐指数
1
解决办法
2730
查看次数

使用Websockets时无法在Spring Controller中获取Session

我正在使用带有Spring MVC Framework的Websockets SockJS.我尝试了正常工作的股票代码示例,但现在我想在我的控制器中获取会话,但我无法找到出路.

Client Code:
$scope.socket = new SockJS("ws/ws"); 
$scope.stompClient = Stomp.over($scope.socket); 
$scope.stompClient.connect("guest", "guest",connectCallback, errorCallback);

//in connectCallback
$scope.stompClient.subscribe('/topic/agent-sendstatus', showScreenPop);

    Java Code:
    @MessageMapping("/topic/agent-sendstatus")
        public void testmethod()
        {
            //How do i get Session here to further implement solution?

            template.convertAndSend("/topic/agent-sendstatus","bcd");
        }

Please suggest.
Run Code Online (Sandbox Code Playgroud)

session sockjs spring-websocket

4
推荐指数
1
解决办法
6619
查看次数

为什么ServletServerContainerFactoryBean在测试时会出现问题?

我正在使用Spring Boot进行Web应用程序.此应用程序还配置为使用WebSocket和处理(非常基本)传入消息.

该应用程序似乎工作正常.问题是我正在进行一些测试.相关部分如下:

//WebManagerApplication.java
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class WebManagerApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebManagerApplication.class, args);
    }
}
//

//WebSocketConfig.java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatWebSocketHandler(), "/chat");
    }

    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192);
        container.setMaxBinaryMessageBufferSize(250_000);
        return container;
    }

    @Bean
    public WebSocketHandler chatWebSocketHandler() {
        Class<ADWebSocketHandler> handlerType = ADWebSocketHandler.class;
        return new PerConnectionWebSocketHandler(handlerType);
    }
}
//

//FooTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {WebManagerApplication.class})
@WebAppConfiguration
public class FooTest {

    @Autowired …
Run Code Online (Sandbox Code Playgroud)

java junit spring-boot spring-websocket

4
推荐指数
2
解决办法
2102
查看次数

在Spring websockets中发送错误消息

我试图通过SockJS在STOMP的Spring websockets中发送错误消息.

我基本上试图实现这里正在做的事情.

这是我的异常处理程序

@MessageExceptionHandler
@SendToUser(value = "/queue/error",broadcast = false)
public ApplicationError handleException(Exception message) throws ApplicationError {
        return  new ApplicationError("test");
}
Run Code Online (Sandbox Code Playgroud)

而且我订阅了

stompClient.subscribe('/user/queue/error', stompErrorCallback, {token: accessToken});
Run Code Online (Sandbox Code Playgroud)

在我的情况下,用户未经过身份验证,但是从此处开始

虽然用户目的地通常意味着经过身份验证的用户,但并不严格要求.与经过身份验证的用户无关的WebSocket会话可以订阅用户目标.在这种情况下,@ SendToUser注释的行为与broadcast = false完全相同,即仅针对发送正在处理的消息的会话.

当我抛出这个错误时,所有这一切都正常,myHandler这是我在websocket config中定义的Websocket Handler.

我有一个ClientInboundChannelInterceptor扩展ChannelInterceptorAdapter,它拦截所有的消息preSend.

如果这个拦截器有任何异常,我想把它扔回发送此消息的用户会话,

public class ClientInboundChannelInterceptor extends ChannelInterceptorAdapter {
    @Autowired
    @Lazy(value = true)
    @Qualifier("brokerMessagingTemplate")
    private SimpMessagingTemplate simpMessagingTemplate;

    @Override
    public Message<?> preSend(Message message, MessageChannel channel) throws IllegalArgumentException{
         if(some thing goes wrong)
           throw new RuntimeException();
    }

    @MessageExceptionHandler
    @SendToUser(value …
Run Code Online (Sandbox Code Playgroud)

spring stomp spring-messaging spring-websocket

4
推荐指数
1
解决办法
3924
查看次数

弹簧websocket与sockjs和stomp客户端设计

我正在将spring web-socket集成到Web应用程序中.而且我想将这个用于两次在ajax中花费很长时间的调用.根据我的理解,我看到有关于如何进行此操作的不同设计选择.我正在考虑以下问题,你能告诉我什么是最好的选择,如果是这样的话

1)一旦用户通过SockJS登录应用程序并打开套接字连接,并使用此连接发送消息并订阅我想要进行的两个调用.我对此设计的一个问题是,如果用户只是关闭浏览器,套接字连接是否会保持打开状态?

2)为每个呼叫打开一个套接字连接,并在收到消息后将其关闭,但这里每次都需要大量资源来建立连接.

我对spring-websocket,SockJS和STOMP的东西很新,所以让我知道我的理解在任何地方都是错的?

提前致谢

java stomp web sockjs spring-websocket

4
推荐指数
1
解决办法
1770
查看次数

弹簧安全启动弹簧websocket失败,"没有bean命名'stompWebSocketHandlerMapping'被定义'

spring boot version 1.3.0发布.

错误日志是

13:00:50.888 [main]错误osboot.SpringApplication - 应用程序启动失败org.springframework.beans.factory.NoSuchBeanDefinitionException:org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory)中未定义名为'stompWebSocketHandlerMapping'的bean .java:698)〜[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE] org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)~ [spring- bean-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)〜[spring-beans-4.2.3.RELEASE.jar :4.2.3.RELEASE] org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)〜[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org .springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1057)~ [spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]在org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer.afterSingletonsInstantiated(AbstractSecurityWebSocketMessageBrokerConfigurer.java:222)〜[spring-security-config-4.0.3.RELEASE.jar:4.0.3 .RELEASE]在org.springframework.context的org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:792)〜[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE] .support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)〜[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE] org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java: 537)〜[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE] org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)~ [spring-boot-1.3 or.0.RELEASE.jar:1.3.0.RELEASE]在org.springframework.boot.Spri 在org.springframework.boot.SpringApplication.doRun(SpringApplication.java:347)〜[spring]的ngApplication.refresh(SpringApplication.java:752)〜[spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE] -boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]在org.springframework.boot.SpringApplication.run(SpringApplication.java:295)〜[spring-boot-1.3.0.RELEASE.jar:1.3. 0.RELEASE]在com.d2js.platform.manager.Main.main(Main.java:28)[classes /:na]

我的websocket配置类

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private final TeacherMonitorHandler teacherMonitorHandler = null;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(teacherMonitorHandler, "/websocket/teacherMonitor");
    }
}
Run Code Online (Sandbox Code Playgroud)

websocket安全配置类:

@Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
    @Override
    protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
        messages.anyMessage().permitAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

spring spring-security spring-boot spring-websocket

4
推荐指数
1
解决办法
1584
查看次数

使用示例ReactorNettyWebSocketClient

New Spring在Spring文档中有一些WebSocketClient示例。

WebSocketClient client = new ReactorNettyWebSocketClient();
client.execute("ws://localhost:8080/echo"), session -> {... }).blockMillis(5000);
Run Code Online (Sandbox Code Playgroud)

但这很短,也不清楚:

  1. 如何向服务器(订阅频道)发送消息?
  2. 然后处理传入的流并发出Flux消息?
  3. 连接中断时重新连接到服务器?

有人可以提供更复杂的例子吗?

UPD。我试图做类似的事情:

public Flux<String> getStreaming() {

    WebSocketClient client = new ReactorNettyWebSocketClient();
    EmitterProcessor<String> output = EmitterProcessor.create();
    Flux<String> input = Flux.just("{ event: 'subscribe', channel: 'examplpe' }");

    Mono<Void> sessionMono = client.execute(URI.create("ws://api.example.com/"),
            session -> session
                    .send(input.map(session::textMessage))
                    .thenMany(session.receive().map(WebSocketMessage::getPayloadAsText).subscribeWith(output).then())
                    .then());

    return output.doOnSubscribe(s -> sessionMono.subscribe());
}
Run Code Online (Sandbox Code Playgroud)

但这仅返回一条消息。就像我没有订阅。

spring-boot spring-websocket spring-webflux

4
推荐指数
1
解决办法
1014
查看次数

Spring Boot + Spring Web套接字+ RabbitMQ Web STOMP

我正在努力在应用程序中添加实时通知

我已经用-Spring Boot-Spring WebSocket-SockJS-RabbitMQ STOMP插件完成了POC

我阅读了有关RabbitMQ Web STOMP的文章,并希望对此进行POC。但它说,自3.7版以来,已删除了对SockJS websocket仿真的支持。

是否有带有或不带有SockJS的Spring WebSocket + RabbitMQ Web STOMP的示例。

请帮忙。

参考链接:

http://www.rabbitmq.com/stomp.html

http://www.rabbitmq.com/web-stomp.html

https://spring.io/guides/gs/messaging-stomp-websocket/

java rabbitmq sockjs spring-boot spring-websocket

4
推荐指数
1
解决办法
3113
查看次数