前端创建链接时官方提供的构造函数
html
var aWebSocket = new WebSocket(url, [protocols]);
url:要连接的URL;这应该是WebSocket服务器将响应的URL。
protocols:可选;一个协议字符串或者一个包含协议字符串的数组。这些字符串用于指定子协议,这样单个服务器可以实现多个WebSocket子协议(例如,您可能希望一台服务器能够根据指定的协议(protocol)处理不同类型的交互)。如果不指定协议字符串,则假定为空字符串。
websocket携带参数支持两种方式
在url后面拼接,类似以get请求
javascript
var socket = new WebSocket('ws://example.com/socket?token=' + YOUR_TOKEN);
使用protocols,token不要有特殊符号之类,逗号,横杠等也不要有,要不前端构造函数会报错
javascript
var webSocket = new WebSocket(url,[token]);
后台获取
java
package cn.bool.business.framework.websocket.core.security;
import cn.bool.business.framework.security.core.LoginUser;
import cn.bool.business.framework.security.core.filter.TokenAuthenticationFilter;
import cn.bool.business.framework.security.core.util.SecurityFrameworkUtils;
import cn.bool.business.framework.websocket.core.util.WebSocketFrameworkUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.server.HandshakeInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* 登录用户的 {@link HandshakeInterceptor} 实现类
*
* 流程如下:
* 1. 前端连接 websocket 时,会通过Sec-WebSocket-Protocol协议传输token
*/
public class LoginUserHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) { // HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
// String header = request.getHeader(WS_LOGIN_USER_HEADER); // 不强转也可以使用 HttpHeaders headers = request.getHeaders();
List<String> list = headers.get("Sec-WebSocket-Protocol");
if (CollectionUtil.isNotEmpty(list)) {
String token = list.get(0);
} // 自己项目中登录校验逻辑 TODO
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception exception) { // 需要将前端自定义协议头Sec-WebSocket-Protocol原封不动返回回去,否则会报错
HttpServletRequest httpRequest = ((ServletServerHttpRequest) request).getServletRequest();
HttpServletResponse httpResponse = ((ServletServerHttpResponse) response).getServletResponse();
if (StringUtils.isNotEmpty(httpRequest.getHeader("Sec-WebSocket-Protocol"))) {
httpResponse.addHeader("Sec-WebSocket-Protocol", httpRequest.getHeader("Sec-WebSocket-Protocol"));
}
}
}