本文介绍了Spring Websockets STOMP - 获取客户端 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法获取STOMP客户端IP地址?我正在拦截入站频道,但我看不到任何检查IP地址的方法.
Is there any way to obtain STOMP client IP address? I am intercepting inbound channel but I cannot see any way to check the ip address.
感谢任何帮助.
推荐答案
您可以在使用 HandshakeInterceptor
握手期间将客户端 IP 设置为 WebSocket 会话属性:
You could set the client IP as a WebSocket session attribute during the handshake with a HandshakeInterceptor
:
public class IpHandshakeInterceptor implements HandshakeInterceptor {
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
// Set ip attribute to WebSocket session
attributes.put("ip", request.getRemoteAddress());
return true;
}
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception exception) {
}
}
使用握手拦截器配置您的端点:
Configure your endpoint with the handshake interceptor:
@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").addInterceptors(new IpHandshakeInterceptor()).withSockJS();
}
并使用标头访问器获取处理程序方法中的属性:
And get the attribute in your handler method with a header accessor:
@MessageMapping("/destination")
public void handlerMethod(SimpMessageHeaderAccessor ha) {
String ip = (String) ha.getSessionAttributes().get("ip");
...
}
这篇关于Spring Websockets STOMP - 获取客户端 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!