websocket Web Socket端点

ilmyapht  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(138)

大家好,我有一些问题弄清楚一些WebSocket端点。我试图建立一个基本的聊天应用程序,以帮助我获得对websocket的理解。
我正在运行一个Java 8 Sping Boot WebSocket服务器,该服务器运行在http://localhost:8080上,用于测试目的。

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketMessageConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry) {
        WebSocketMessageBrokerConfigurer.super.registerStompEndpoints(registry);
        registry.addEndpoint("/websocket").setAllowedOriginPatterns("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry registry) {
        WebSocketMessageBrokerConfigurer.super.configureMessageBroker(registry);
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");
    }
}

@Controller
public class SocketController {

    @MessageMapping("/socket.send")
    @SendTo("/topic/public")
    public SocketMessage sendMessage(@Payload final SocketMessage message) {
        return message;
    }

    @MessageMapping("/socket.newUser")
    @SendTo("/topic/public")
    public SocketMessage newUser(@Payload final SocketMessage message,
                                 SimpMessageHeaderAccessor  headerAccessor) {

        headerAccessor.getSessionAttributes().put("username", message.getSender());
    return message;
    }

}
这是我的配置文件和控制器文件......我的理解是,registerStompEndpoints()提供了端点来设置客户端/服务器之间的会话连接。
前端请求如下所示
从我的javascript前端请求看,这似乎工作得很好。我看到一个很好的日志显示连接到它,但当我试图发送一个新用户或一条消息时,两者似乎都没有正确地到达服务器。我在日志中看不到任何东西,所以我怀疑我的前端端点是不正确的...

const socket = new SockJS('http://localhost:8080/websocket')
stompClient.subscribe('http://localhost:8080/topic/public', onMessageReceived)
stompClient.send("http://localhost:8080/app/socket.newUser",
stompClient.send("http://localhost:8080/app/socket.send", {}, JSON.stringify(chatMessage))

这是我在前端的console.log

>>> SUBSCRIBE
id:sub-0
destination:http://localhost:8080/app/topic/public

>>> SEND
destination:http://localhost:8080/app/socket.newUser
content-length:36

{"sender":"testname","type":"CONNECT"}
btqmn9zl

btqmn9zl1#

感谢Mike“Pomax”Kamermans提供的解决方案。
我的错误是在我的前端代码。
这是我最初的设置。

const socket = new SockJS('http://localhost:8080/websocket')
stompClient.subscribe('http://localhost:8080/topic/public', onMessageReceived)
stompClient.send("http://localhost:8080/app/socket.newUser",
stompClient.send("http://localhost:8080/app/socket.send", {}, JSON.stringify(chatMessage))

它被更改为看起来像....

const socket = new SockJS('http://localhost:8080/websocket')

stompClient.subscribe('/topic/public', onMessageReceived)

stompClient.send("/app/socket.newUser",

stompClient.send("/app/socket.send", {}, JSON.stringify(chatMessage))```

This was the cause of my issues. Thanks for the help!

相关问题