websocket是Html5新增加特性之一,目的是瀏覽器與服務端建立全雙工的通信方式,解決http請求-響應帶來過多的資源消耗,同時對特殊場景應用提供了全新的實現方式,例如聊天、股票交易、遊戲等對對即時性要求較高的產業領域。
在瀏覽器中透過http僅能實現單向的通訊,comet可以一定程度上模擬雙向通訊,但效率較低,並需要伺服器有較好的支援; flash中的socket和xmlsocket可以實現真正的雙向通信,通過flex ajax bridge,可以在javascript中使用這兩項功能. 可以預見,如果websocket一旦在瀏覽器中得到實現,將會替代上面兩項技術,得到廣泛的使用.面對這種狀況,HTML5定義了WebSocket協議,能更好的節省伺服器資源和頻寬並達到即時通訊。目前各大主流瀏覽器都支援websocket,IE瀏覽器要IE10+
POM依賴,spring4.1.4.RELEASE,spring
<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>4.1.4.RELEASE</version> </dependency>
@Configuration @EnableWebMvc @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { //允许连接的域,只能以http或https开头 String[] allowsOrigins = {"http://www.xxx.com"}; //WebIM WebSocket通道 registry.addHandler(chatWebSocketHandler(),"/ webSocketIMServer").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor()); registry.addHandler(chatWebSocketHandler(), "/sockjs/w ebSocketIMServer").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor()).withSockJS(); } @Bean public ChatWebSocketHandler chatWebSocketHandler() { return new ChatWebSocketHandler(); } @Bean public WebSocketHandshakeInterceptor myInterceptor(){ return new WebSocketHandshakeInterceptor(); } }
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object > attributes) throws Exception { if (request instanceof ServletServerHttpRequest) { attributes.put("username",userName); } return true; } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { } }
public class ChatWebSocketHandler extends TextWebSocketHandler{ private final static List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<WebSocketSession>()); //接收文本消息,并发送出去 @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { chatTextMessageHandler(message.getPayload()); super.handleTextMessage(session, message); } //连接建立后处理 @SuppressWarnings("unchecked") @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.debug("connect to the websocket chat success......"); sessions.add(session); //处理离线消息 } //抛出异常时处理 @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { if(session.isOpen()){ session.close(); } logger.debug("websocket chat connection closed......"); sessions.remove(session); } //连接关闭后处理 @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { logger.debug("websocket chat connection closed......"); sessions.remove(session); } @Override public boolean supportsPartialMessages() { return false; } }
var host = window.location.host; var websocket; if ('WebSocket' in window) { websocket = new ReconnectingWebSocket("ws://" + host + "/webSocketIMServer", null, {debug:true, maxReconnectAttempts:4}); } else if ('MozWebSocket' in window) { websocket = new MozWebSocket("ws://" + host + "/webSocketIMServer"); } else { websocket = new SockJS("http://" + host + "/sockjs/webSocketIMServer"); } websocket.onopen = function(evnt) { console.log("websocket连接上"); }; websocket.onmessage = function(evnt) { messageHandler(evnt.data); }; websocket.onerror = function(evnt) { console.log("websocket错误"); }; websocket.onclose = function(evnt) { console.log("websocket关闭"); }
以上是spring WebSocket的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!