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"; } }
二、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); } }