握手時(shí)出錯(cuò)403
瀏覽器控制臺(tái)錯(cuò)誤提示
Error during WebSocket handshake: Unexpected response code: 403
配置示例
- websocket 注冊(cè)
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(socketHandler, "/test").addInterceptors(new SystemInfoSocketHandshakeInterceptor());
registry.addHandler(socketHandler, "/sockjs/test").addInterceptors(new SystemInfoSocketHandshakeInterceptor())
.withSockJS();
}
- 握手?jǐn)r截器
@Configuration
public class SystemInfoSocketHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object
> attributes) {
log.info("socket beforeHandshake..");
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
// 業(yè)務(wù)處理
}
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
log.info("socket beforeHandshake..");
}
}
- 客戶端連接
var wsServer = "ws://127.0.0.1:8080";
var webSocket;
if ('WebSocket' in window || 'MozWebSocket' in window) {
webSocket = new WebSocket(wsServer + "/test");
} else {
webSocket = new SockJS(wsServer + "/sockjs/test");
}
webSocket.onerror = function (event) {
console.log("websockt連接錯(cuò)誤")
};
分析
- 連接失敗
- 訪問攔截
- nginx代理
- 跨域
解決
連接問題
如果是連接上面的問題,一般看一下配置是否正確
注意版本問題
訪問攔截
在攔截器中,解除攔截
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
nginx代理
在nginx中配置
proxy_set_header Upgrade $http_upgrade
proxy_set_header Connection "upgrade"
proxy_set_header Host $host
三個(gè)配置
完整配置如下:
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
跨域
添加setAllowedOrigins("*")
解決跨域問題
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(socketHandler, "/test")
.addInterceptors(new SystemInfoSocketHandshakeInterceptor())
.setAllowedOrigins("*");
registry.addHandler(socketHandler, "/sockjs/test")
.addInterceptors(new SystemInfoSocketHandshakeInterceptor())
.setAllowedOrigins("*")
.withSockJS();
}
資料相關(guān)
收錄時(shí)間: 2021/02/03