當(dāng)WebSocket請(qǐng)求獲取請(qǐng)求頭Sec-WebSocket-Protocol不為空時(shí),需要返回給前端相同的響應(yīng),所以就需要處理
解決:在 WebSocketConfig 中新增?modifyHandshake方法,用來(lái)獲取請(qǐng)求頭和為返回響應(yīng)賦值
?
modifyHandshake方法文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-616653.html
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
//獲取請(qǐng)求頭
request.getHeaders().get("Sec-WebSocket-Protocol").get(0);
//當(dāng)Sec-WebSocket-Protocol請(qǐng)求頭不為空時(shí),需要返回給前端相同的響應(yīng)
response.getHeaders().put("Sec-WebSocket-Protocol",list);
/**
*獲取請(qǐng)求頭后的邏輯處理
*/
super.modifyHandshake(sec, request, response);
}
關(guān)鍵點(diǎn):需要在websocketserver的@ServerEndpoint注解中加上configurator = WebSocketConfig.class,也就是上面那個(gè)方法存在的配置文件中文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-616653.html
@Component
@ServerEndpoint(value ="/webSocket/{userId}",encoders = { ServerEncoder.class },configurator = WebSocketConfig.class)
public class WebSocketServer {
/**
* 連接開(kāi)始調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session) throws Exception {}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose(@PathParam(value = "userId") Integer userId,Session session) {}
}
到了這里,關(guān)于WebSocket請(qǐng)求獲取請(qǐng)求頭Sec-WebSocket-Protocol,以及正確返回響應(yīng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!