且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用spring向特定用户发送消息

更新时间:2023-01-15 19:02:33

您可以使用第一种方法来设置用户名.首先,您需要将拦截器添加到您的 StompEndpointRegistry 类中,然后您可以从 属性 映射中确定用户并返回 主体.

You can use your first approach to set the Username. First you need add the interceptor to your StompEndpointRegistry class and after that you can determine User from the attributes Map and return the Principal.

代码如下:

HttpSessionHandshakeInterceptor 用于拦截 Http 属性并在 DefaultHandshakeHandler 类中提供它们

HttpSessionHandshakeInterceptor is Used for Intercepting the Http attributes and provide them in the DefaultHandshakeHandler class

@Configuration
@EnableWebSocketMessageBroker
@EnableWebMvc
@Controller
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {


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

}

public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/chat")
     //Method .addInterceptors for enabling interceptor
    .addInterceptors(new HttpSessionHandshakeInterceptor())
    .setHandshakeHandler(new MyHandler())
    .withSockJS();
}

class MyHandler extends DefaultHandshakeHandler{


    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
            Map<String, Object> attributes) {

//Get the Username object which you have saved as session objects

    String name  = (String)attributes.get("name");

 //Return the User
    return new UsernamePasswordAuthenticationToken(name, null);
    }
  }

}