Learning WebSocket (a): The simple use of Spring websocket

Source: Internet
Author: User

1. What is WebSocket?

The WebSocket protocol defines a new feature of a Web application that implements full-duplex communication between the server and the client. Full-duplex communication means that both sides of the communication can send and receive information interactively. It is a new technology that makes Web applications more interactive, such as Java applets, XMLHttpRequest, Adobe Flash, ActiveXObject, and more.

In the implementation of the connection, the browser and the server through the TCP three handshake to establish connections. If the connection to the server is successful, the browser sends a handshake request over HTTP, and if the server consents to a handshake, the client and the service can send messages to each other. HTTP is used only to start the handshake, and once the handshake connection is successfully established, HTTP does not participate in data transfer and uses a TCP connection to transfer the data.

2, the past and the server interaction several ways

  Long polling

Long polling is where the client periodically sends requests to the server at a fixed time, typically the length of the interval is affected by the update frequency of the service side and the time the client processes the updated data. The disadvantage of this way is obvious, is that the browser to constantly send requests to the server to obtain the latest information, causing the server pressure is too large, occupy broadband resources.

  Using streaming AJAX

Streaming Ajax is a long-connection maintenance mechanism implemented via AJAX. The primary purpose is to read the returned data during the data transfer and not close the connection.

  The way of the IFRAME

An IFRAME can nest a sub-page in a page, and the server can continue to transfer data to the client by pointing the src of the IFRAME to a long-connected request address.

3. When to use WebSocket?

The most suitable Web application for WebSocket is those that require high-frequency, low-latency exchange of information on both the client and server side.

4, how to use WebSocket?

Spring provides a WebSocket API that adapts to various websocket engines, such as Tomcat (7.0.47+) and GlassFish (4.0+), and WebSocket (jetty) that supports native 9.0+. Different browsers support the WebSocket, and if the browser WebSocket is not supported, then you can use Socketjs instead of websocket.

  Create and configure Websockethandler

The Websockethandler is used to process websocket messages.

 Public class extends Textwebsockethandler {    @Override    publicvoid  handletextmessage ( Websocketsession session, TextMessage message) {
Session.sendmessage (message); }}

  Create and configureHandshakeInterceptor

  HandshakeInterceptorUsed to process pre-and post-handshake work.

 Public classHandshakeinterceptorextendsHttpsessionhandshakeinterceptor {@Override Public voidAfterhandshake (serverhttprequest request, serverhttpresponse response, Websockethandler Wshandler, Exception ex) { System.out.println ("After handshake"); Super. Afterhandshake (Request, Response, Wshandler, ex); } @Override Public BooleanBeforehandshake (serverhttprequest request, serverhttpresponse response, Websockethandler wshandler,map<string, Object>attributes)throwsException {System.out.println ("Before handshake");
return Super. Beforehandshake (Request, response, Wshandler, attributes); }}

  Configure Spring-websocket.xml at the same time

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:websocket= "Http://www.springframework.org/schema/websocket"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/websocket Http://www.springframework.org/schema/websocket/spring-websocke T.xsd ">                   <websocket:handlers>        <websocket:mappingHandler= "MyHandler"Path= "/myhandler"/>        <websocket:handshake-interceptors>            <Beanclass= "Org.springframework.samples.HandshakeInterceptor"></Bean>        </websocket:handshake-interceptors>    </websocket:handlers>                 <BeanID= "MyHandler"class= "Org.springframework.samples.MyHandler"></Bean>      </Beans>

  Add JavaScript on the page

<script type= "Text/javascript" >
Websocket-demo is Project namevarurl = ' ws://' + window.location.host + '/websocket-demo/myhandler '; varSock =NewWebSocket (URL); Sock.onopen=function() {Console.log (' Opening '); SayHello (); }; Sock.onmessage=function(e) {alert (' Received message: ' +e.data); }; Sock.onclose=function() {Console.log (' Closing '); }; functionSayHello () {Console.log (' Sending hello! '); Sock.send ("Hello!"); }</script>

Places to be aware of:

1, the application Server version, if the version is too low to support websocket

2, JavaScript websocket URL should and spring-websocket.xml <websocket:mapping path= "" > Consistent

Learning WebSocket (a): The simple use of Spring websocket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.