WebSocket遇到的一些問題

一 、Nginx配置websocket
 
爲了解決Nginx轉發不能進行websocket通訊問題
將nginx配置文件添加以下內容:
 
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server 192.168.100.10:8010;
}
server {
listen 8020;
location / {
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
}

 

 
2、Nginx攔截器解決瀏覽器兼容問題
 
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
 
private final Logger logger = LoggerFactory.getLogger(HandshakeInterceptor.class);
 
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
logger.info("==============Before Handshake===============");
/** 在攔截器內強行修改websocket協議,將部分瀏覽器不支持的 x-webkit-deflate-frame 擴展修改爲 permessage-deflate */
if(request.getHeaders().containsKey("Sec-WebSocket-Extensions")){
request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
}
return super.beforeHandshake(request, response, wsHandler, attributes);
}
 
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
logger.info("==============After Handshake===============");
super.afterHandshake(request, response, wsHandler, ex);
}
 
}
相關文章
相關標籤/搜索