Scenario
Websocket is one of the new features of Html5. The purpose is to establish a full-duplex communication method between the browser and the server to solve the excessive resource consumption caused by http request-response. At the same time, it provides new implementation methods for special scenario applications, such as chat, stock trading, games and other industries that require high real-time performance.
Background
Only one-way communication can be achieved through http in the browser. Comet can simulate two-way communication to a certain extent, but the efficiency is low and a server is required. There is good support; socket and xmlsocket in flash can achieve true two-way communication. Through flex ajax bridge, these two functions can be used in javascript. It is foreseeable that if websocket is once in the browser If implemented, it will replace the above two technologies and be widely used. Faced with this situation, HTML5 defines the WebSocket protocol, which can better save server resources and bandwidth and achieve real-time communication. At present, all major mainstream browsers support websocket, IE browser requires IE10+
1. POM dependency
POM dependency, spring4.1.4.RELEASE, spring Please add core dependencies by yourself. The following are websocket related jar
<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>
2. WebSocket entrance
@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(); } }
Implement the WebSocketConfigurer interface and override the registerWebSocketHandlers method. This is a core implementation method , configure the websocket entrance, allowed access domains, registered Handler, SockJs support and interceptor.
registry.addHandler registration and routing function, when the client initiates a websocket connection, the /path is handed over to the corresponding handler for processing without implementing specific business logic, which can be understood as collection and task distribution center.
setAllowedOrigins(String[] domains) allows the specified domain name or IP (including port number) to establish a long connection. If you only allow access to your own domain name, you can easily set it here. If the "*" sign is used without time limit, if a domain name is specified, it must start with http or https.
addInterceptors, as the name suggests, is to add interceptors to the handler. We can add our own logic code before and after calling the handler.
spring websocket also supports STOMP protocol, I will share it next time.
3. Interceptor implementation
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<string> 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) { } }</string>
beforeHandshake, handle the method before calling the handler. Commonly used to register user information, bind WebSocketSession, and obtain WebSocketSession to send messages based on user information in the handler.
4. Handler processing class
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; } }</websocketsession></websocketsession>
5. Client connection
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 is used here, and extensions are added to the browser's own websocket, such as reconnection , connection timeout, failed reconnection interval, maximum number of connection attempts, etc.
Project homepage:ReconnectingWebSocket
The above is the detailed content of Detailed introduction to spring WebSocket. For more information, please follow other related articles on the PHP Chinese website!

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version