標籤:
我最近正在做一個基於websocket的webQQ,最後代碼會開源帶github上,所以過程中我就不貼所有的代碼啦~就貼問題的關鍵。
首先先搞清一個流程:WebSocket在建立串連時第一步其實是以HTTP協議的面目進行握手的:
1.用戶端發送websocket請求,此時發送的還是http包。
2.如果伺服器支援websocket,那麼就將http轉變為websocket。
3.此時串連建立,伺服器和用戶端可以雙向即時進行通訊。
那麼我們該怎麼拿到HttpSession呢?觀察上面整個過程發現只有在第一步的時候才能得到,於是乎websocket給了我們一個方法介入websocket初始化的過程。
首先要繼承ServerEndpointConfig,並實現 modifyHandshake方法:
import javax.servlet.http.HttpSession;import javax.websocket.HandshakeResponse;import javax.websocket.server.HandshakeRequest;import javax.websocket.server.ServerEndpointConfig; public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator{ @Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession)request.getHttpSession(); config.getUserProperties().put(HttpSession.class.getName(),httpSession); }}
然後在實現ServerEndPoint時,增加configurator的參數,再這樣擷取即可:
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
如何在WebSocket類中訪問Session