【问题标题】:SpringBoot web socket server not respondingSpring Boot websocket服务器没有响应
【发布时间】:2021-11-03 05:20:23
【问题描述】:

我正在努力在 springboot 中实现 web 套接字,我遵循了 spring 在文档中给出的示例,在连接到套接字后,我没有收到来自服务器的任何响应。我尝试将我的前端与 spring boot 应用程序分开,即两个应用程序在不同的端口上运行。 控制器-

@CrossOrigin
@RestController
public class GreetingController {
    @MessageMapping("/Hello")
    @SendTo("/topic/greetings")
    public  Greeting greeting(HelloMessage message){
        return new Greeting("Hello, "+ HtmlUtils.htmlEscape(message.getName()));
    }
}

模型类-

@Data
@NoArgsConstructor
@AllArgsConstructor
public class HelloMessage {
    private String name;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Greeting {
    private String message;
}

配置类-

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry){
        registry.addEndpoint("/stomp-endpoint").setAllowedOrigins("*").withSockJS();
    }

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

前端-

function connect() {
    var socket = new SockJS('http://localhost:8080//stomp-endpoint');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('http://localhost:8080//topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body));
        });
    });
}

发送方法-

function sendName() {
    stompClient.send("http://localhost:8081/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}

我得到的输出 -

我收到了connected to server undefined,但没有收到来自服务器的响应,springboot 控制台中也没有错误日志或 sysout。

当我连接到套接字时,它连接正常,但是在发送消息后,我没有得到响应,即使 sysout 也无法在 java 代码中工作。 我该如何解决这个问题!

【问题讨论】:

  • 可以发一下“send”方法吗?
  • @katiforis 抱歉耽搁了,我已经在代码中添加了发送方法

标签: java spring spring-boot


【解决方案1】:
  • 如果你使用stompClient.subscribe,在后端你应该使用@SubscribeMapping来接收
  • 你可以试试stompClient.send('/app/Hello',{},'')

【讨论】:

  • 感谢您的回答,但它对我不起作用,我将 MessageMapping 替换为 SubscribeMapping 但仍然遇到同样的问题“服务器没有响应”,我在问题中添加了它的快照你能建议我用其他方法吗
  • 试试这个:helloHello,可能区分大小写,将 http://localhost:8081/app/hello 更改为 /app/Hello
猜你喜欢
  • 2018-07-05
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
  • 2019-05-02
  • 2015-11-09
  • 2021-08-27
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多