springWebSocket的细致介绍-
场景
websocket是Html5新添加特性之一,目的是阅读器与办事端创立全双工的通讯方式,解决http要求-相应带来过多的资源耗损,同时对特别场景利用供给了全新的实现方式,比方谈天、股票交易、游戏等对对实时性请求较高的行业领域。
配景
在阅读器中通过http仅能实现单向的通讯,comet可以一定程度上模拟双向通讯,但效率较低,并需要办事器有较好的支撑; flash中的socket和xmlsocket可以实现真正的双向通讯,通过 flex ajax bridge,可以在javascript中运用这两项功能. 可以预感,要是websocket一旦在阅读器中得到实现,将会替换上面两项技术,得到宽泛的运用.面临这种情况,HTML5定义了WebSocket协定,能更好的节俭办事器资源和带宽并达到实时通信。当前各大主流阅读器都支撑websocket,IE阅读器要IE10+
一、POM依赖
POM依赖,spring4.1.4.RELEASE,spring中心依赖请自行增加,下面是websocket相干jar
javax.websocket javax.websocket-api1.0 provided org.springframework spring-websocket4.1.4.RELEASE
二、WebSocket入口
@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(); } }
实现WebSocketConfigurer接口,重写registerWebSocketHandlers办法,这是一个中心实现办法,配置websocket入口,允许拜访的域、注册Handler、SockJs支撑和拦截器。
registry.addHandler注册和路由的功能,当客户端发起websocket连贯,把/path交给对应的handler处置,而不实现概括的业务逻辑,可以了解为收集和任务分发核心。
setAllowedOrigins(String[] domains),允许指定的域名或IP(含端标语)创立长连贯,要是只允许自家域名拜访,这里轻松设定。要是不限时运用"*"号,要是指定了域名,则必需要以http或https开头。
addInterceptors,望文生义就是为handler增加拦截器,可以在调取handler先后参加我们本人的逻辑代码。
spring websocket也支撑STOMP协定,下回再分享。
三、拦截器实现
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Mapattributes) throws Exception { if (request instanceof ServletServerHttpRequest) { attributes.put("username",userName); } return true; } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { } }
beforeHandshake,在调取handler前处置办法。常用在注册会员信息,绑定WebSocketSession,在handler里依据会员信息猎取WebSocketSession发送新闻。
四、Handler处置类
public class ChatWebSocketHandler extends TextWebSocketHandler{ private final static Listsessions = Collections.synchronizedList(new ArrayList ()); //接收文本新闻,并发送出去 @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关闭"); }
这里用到了ReconnectingWebSocket.js,对阅读器自带websocket增加了扩展,例如重连,连贯超不时间,失败重连隔断,尝试连贯最大次数等。
项目主页:ReconnectingWebSocket
以上就是spring WebSocket的细致介绍的细致内容,更多请关注 百分百源码网 其它相干文章!