Spring WebSocket uses

Source: Internet
Author: User
Tags comparable stomp

The project used the message of real-time push, check the data used to spring WebSocket, looking for a lot of information, or feel the official Help document written most clearly, is summarized below.

There are also two very classic examples: one is https://spring.io/guides/gs/messaging-stomp-websocket/, attached see the download method in the article; another example is https://github.com /rstoyanchev/spring-websocket-portfolio can be downloaded by itself.

WebSocket Support

This part of the reference documentation covers Spring Framework ' s support for Websocket-style messaging in web Applicatio NS including use of STOMP as a application level WebSocket sub-protocol.

Section 21.1, "Introduction" establishes a frame of the mind in which to is about WebSocket, covering adoption, Design considerations, and thoughts in when it is a good fit.

Section 21.2, "WebSocket APIs" reviews the Spring WebSocket API on the Server-side while section 21.3, "Sockjs fallback Opt Ions "explains the SOCKJS protocol and shows how to configure and use it.

Section 21.4.1, "Overview of STOMP" introduces the STOMP messaging. Section 21.4.2, ' Enable STOMP over WebSocket ' demonstrates how to configure STOMP support in Spring. Section 21.4.4, "Annotation Message Handling" and the following sections explain I-write annotated message handling m Ethods, send messages, choose message Broker options, as as and work with the special "user" destinations. Finally, section 21.4.16, "Testing annotated Controller Methods" lists three approaches to testing stomp/websocket tions. 21.1 Introduction

The WebSocket protocol RFC 6455 defines a important new capability for Web Applications:full-duplex, two-way Communicati On between client and server. It is a exciting new capability on the heels a long history of techniques to make the web more interactive including J Ava applets, XMLHttpRequest, Adobe Flash, ActiveXObject, various Comet techniques, server-sent events, and others.

A proper introduction of the WebSocket protocol is beyond the scope of this document. At a minimum however it's important to understand so HTTP is used only for the initial handshake, which relies on a mech Anism built into HTTP to request a protocol upgrade (or in this case a protocol switch) to which the server can respond WI Th HTTP status (switching protocols) if it agrees. Assuming the handshake succeeds the TCP socket underlying the HTTP upgrade request remains open and both client and server can use it to send messages to each other.

The Spring Framework 4 includes a new Spring-websocket module with comprehensive websocket support. It is compatible with the Java WebSocket APIs Standard (JSR-356) and also provides additional value-add as explained in the Rest of the introduction. 21.1.1 WebSocket fallback Options

An important challenge to adoption are the lack of support for WebSocket in some. Notably the "the" I Internet Explorer version to support WebSocket is version (* Http://caniuse.com/websockets for Supp ORT by browser versions). Furthermore, some restrictive proxies may is configured in ways this either preclude the attempt to do HTTP upgrade or oth Erwise break connection After some time because it has remained for opened long. A Good overview on this topic from Peter Lubbers are available in the InfoQ article ' how HTML5 Web Sockets interact with Pr Oxy Servers ".

Therefore to builds a WebSocket application today, fallback options are required to simulate the WebSocket API where necess ary. The Spring Framework provides such transparent fallback options based on the SOCKJS protocol. These options can is enabled through configuration and do not require modifying the application otherwise. 21.1.2 A Messaging Architecture

Aside from short-to-midterm adoption challenges with the using WebSocket brings up important design considerations that are import Ant to recognize early on, especially into contrast to what we know about building Web applications today.

Today REST are a widely accepted, understood, and supported architecture for building Web applications. It is a architecture this relies on has many URLs (nouns), a handful of HTTP methods (verbs), and other principles suc h as using hypermedia (links), remaining stateless, etc.

By contrast a WebSocket application could use a single URL only for the initial HTTP handshake. All messages thereafter share and flows on the same TCP connection. This is points to a entirely different, asynchronous, Event-driven, messaging architecture. One is a very closer to traditional messaging applications (e.g. JMS, AMQP).

Spring Framework 4 includes a new spring-messaging module with key abstractions from the spring integration project such a s message, Messagechannel,messagehandler and others the can serve as a foundation for such a messaging architecture. The module also includes a set of annotations for mapping messages to methods, similar to the Spring MVC annotation Programming model. 21.1.3 sub-protocol Support in WebSocket

WebSocket does imply a messaging architecture but not does the "use of" any mandate specific. It is a very thin layer over TCP this transforms a stream of bytes into a stream of messages (either text or binary) and n OT much more. It is up to applications to interpret the meaning's a message.

Unlike HTTP, which is a application-level protocol, in the WebSocket protocol there are simply not enough information in a N Incoming message for the a framework or container to know, to route it or process it. Therefore WebSocket is arguably too low level for anything but a very trivial. It can be done, but it would likely lead to creating a framework on top. This is comparable to how most Web applications today are written using a web framework rather than the Servlet API alone.

For this reason the WebSocket RFCs defines the use of sub-protocols. During the handshake, client and server can use the header Sec-websocket-protocol to agree on a sub-protocol, i.e. a Highe R, Application-level protocol to use. The use of a sub-protocol isn't required, but even if not used, applications'll still need to choose a message format T Hat both client and server can understand. This format can be custom, framework-specific, or a standard messaging protocol.

Spring Framework provides support for using STOMP-A simple, messaging protocol originally created for use in scripting L Anguages with frames inspired by HTTP. STOMP is widely support and very suited for use over WebSocket and over the web. 21.1.4 Should I use WebSocket?

With the "all" design considerations surrounding the "use of WebSocket", it is reasonable to ask if it appropriate to use ?

The best fit for WebSocket are in Web applications where client and server need to exchange events at high frequency and at Low latency. Prime candidates include but are not limited to applications in finance, games, collaboration, and others. Such applications are both very sensitive to time delays and also need to exchange a wide variety of messages in high freq Uency.

For other application types, however, this May is the case. For example, a news or social feeds that shows breaking news as they become available may is perfectly okay with simple pol Ling once every few minutes. Here latency is important, but it are acceptable if the news takes a few minutes to appear.

Even in cases where latency is crucial, if the volume of messages are relatively low (e.g. monitoring network) Use of long polling should to considered as a relatively simple alternative this works reliably and are comparable by Effi Ciency (again assuming the volume of messages is relatively low).

It is the combination of both-latency and high frequency of messages, can make the use of the WebSocket protocol C Ritical. Even in such applications, the choice remains whether-all client-server communication should is done through MES Sages as opposed to using HTTP and REST? The answer is going to vary by application, however, it are likely that some functionality the May was exposed over both ET and as a REST API in order to provide clients with alternatives. Furthermore, a REST API call could need to broadcast a message to interested clients connected via WebSocket.

Spring Framework allows @Controller and @RestController classes to have both HTTP request handling and WebSocket message H Andling methods. Furthermore, a Spring MVC request handling method, or any application to that matter, can easily broadcast a Messa GE to all interested WebSocket clients or to a specific user. 21.2 WebSocket API

The Spring Framework provides a WebSocket API designed to adapt to various WebSocket. For example, it runs on JSR-356 runtimes such as Tomcat (7.0.47+), GlassFish (4.0+) and Wildfly (8.0+) but can also adapt To other WebSocket runtimes such as the Jetty (9.1+) native WebSocket.

As explained in the introduction, direct use of a WebSocket API was too low level for applications-until assumptions Made about the format of a message there are little a framework can do to interpret messages or route them via annotations. This is why applications should consider the using a sub-protocol and Spring ' s STOMP over WebSocket support.

When using a higher level protocol, the details of the WebSocket API become less relevant, much like the details of the TCP Co Mmunication are not exposed to applications when using HTTP. Nevertheless this section covers the details of using WebSocket directly.

21.2.1 Create and Configure a websockethandler

Creating a WebSocket server is as simple as implementing Websockethandler or more likely extending either Textwebsockethan Dler Orbinarywebsockethandler:

Import Org.springframework.web.socket.WebSocketHandler;
Import org.springframework.web.socket.WebSocketSession;
Import Org.springframework.web.socket.TextMessage;

The public class MyHandler extends Textwebsockethandler {@Override the public
    void Handletextmessage ( Websocketsession session, TextMessage message) {
        //...}}

There is dedicated WebSocket Java-config and XML namespace support for mapping the above WebSocket handler at a specific U Rl:

Import Org.springframework.web.socket.config.annotation.EnableWebSocket;
Import Org.springframework.web.socket.config.annotation.WebSocketConfigurer;
Import Org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket Public
class Websocketconfig implements Websocketconfigurer {

    @Override Public
    void Registerwebsockethandlers (Websockethandlerregistry registry) {
        Registry.addhandler MyHandler ( ), "/myhandler");

    @Bean public
    Websockethandler MyHandler () {return
        new MyHandler ();
    }

}

XML configuration equivalent:

<beans xmlns= "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.or G/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org /schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd "> <websocket:han dlers> <websocket:mapping path= "/myhandler" handler= "MyHandler"/> </websocket:handlers> &l T;bean id= "MyHandler" class= "Org.springframework.samples.MyHandler"/> </beans> 

The above is to use in Spring MVC applications and should to included in the configuration of A dispatcherservlet . However, Spring ' s WebSocket support does not depend on spring MVC. It is relatively integrate a websockethandler into other HTTP serving environments with the help OF&NB SP;

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.