近期在做一款点餐软件时 遇到socket报错
报错代码
VM8 asdebug.js:1
WebSocket connection to 'ws://192.168.22.88:34625/ws/desk/order/1/oOuTk5EuSPDlyKNv-AmM4zpquE7Y'
failed: Error during WebSocket
handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received(env: Windows,mp,1.05.2107162; lib: 2.18.0)
问题分析
这个是由websocket规范要求导致的,在socket简历 阶段,必须返回 Sec-WebSocket-Protocol在请求头中,并且必须有值;
解决方案
package com.lqjava.restaurant.serverapp.sys.config.websocket;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order(1)
@Component
@WebFilter(filterName = "WebsocketFilter", urlPatterns = "/ws/**")
public class WebSocketFilter implements Filter{
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
String token = ((HttpServletRequest) servletRequest).getHeader("Sec-WebSocket-Protocol");
response.setHeader("Sec-WebSocket-Protocol",token);
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
|