Go Spring WebSocket Tutorials

Source: Internet
Author: User
Tags stomp

The learning background knew WebSocket long ago, but there was little support for it either by the browser or by the development technology. However, Spring4 suddenly released, let me a bright, Spring4 directly support WebSocket. For spring I still like, it makes Java Web Development quite artistic, this support websocket and my appetite, so immediately went to study. The premise of this article is based on the understanding of the Java EE programming, the use of spring, heard of WebSocket, if the previous 3 points we do not understand, you can first to fill the knowledge. WebSocket is not very common, the server and browser are required, but the use of some of the following technologies, you can reduce the requirements of the browser, but the requirements of the server container is relatively high, specifically which servers are easy to support WebSocket can Baidu a bit. Step One: Configure spring If you're using maven like me, you just need to add the following dependencies to the Pom.xml file:
    <properties> <spring.version>4.0.0.RELEASE</spring.version> </properties> &LT;DEP endencies> <!--spring mvc--> <dependency> <groupid>org.springframework</g Roupid> <artifactId>spring-core</artifactId> <version>${spring.version}</ver sion> </dependency> <dependency> <groupid>org.springframework</groupid&gt            ; <artifactId>spring-web</artifactId> <version>${spring.version}</version> </de pendency> <dependency> <groupId>org.springframework</groupId> <artifa Ctid>spring-webmvc</artifactid> <version>${spring.version}</version> </dependenc Y> <!--jstl--<dependency> <groupId>jstl</groupId> <a Rtifactid&gT;jstl</artifactid> <version>1.2</version> </dependency> <!--spring Test box Racks-<dependency> <groupId>org.springframework</groupId> <artifactid& Gt;spring-test</artifactid> <version>${spring.version}</version> <scope>test </scope> </dependency> <!--Spring Database Operations Library--<dependency> <groupi D>org.springframework</groupid> <artifactId>spring-jdbc</artifactId> <versio n>${spring.version}</version> </dependency> <dependency> <groupid>juni            T</groupid> <artifactId>junit</artifactId> <version>4.8.2</version> <scope>test</scope> </dependency> <!--Spring WebSocket Library--<depen Dency> <groupid>org.springframework</groupid> <artifactId>spring-websocket</artifactId> <version>${spring.version}</version> </dependency> <dependency> <gro Upid>org.springframework</groupid> <artifactId>spring-messaging</artifactId> &L T;version>${spring.version}</version> </dependency> <!--Jackson for JSON operation--<d Ependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactid>jackson-da tabind</artifactid> <version>2.3.0</version> </dependency> <dependency > <groupId>commons-fileupload</groupId> <artifactid>commons-fileupload</arti            factid> <version>1.2.2</version> </dependency> <dependency> <groupid>commons-Io</groupid> <artifactId>commons-io</artifactId> <version>2.2</version&gt        ; </dependency> <!--use Ali's connection pool--<dependency> <groupid>com.alibaba</group id> <artifactId>druid</artifactId> <version>1.0.4</version> </d ependency> <!--MySQL connector--> <dependency> <groupid>mysql</groupid&gt            ; <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> &LT;/DEP Endency> </dependencies>

Spring configuration I will not post it all, can go to GitHub to see, address I will be posted below.

Step Two: Configure WebSocket I use the Configurer class and annotation for websocket configuration. First you create a class, inherit websocketmessagebrokerconfigurer, and add annotation to the class: @Configuration and @EnableWebSocketMessageBroker. In this way, spring will use this class as a configuration class and open WebSocket.
@Configuration @enablewebsocketmessagebrokerpublic class Websocketconfig implements websocketmessagebrokerconfigurer{    @Override public    void Registerstompendpoints (stompendpointregistry Registry) {        //Add this endpoint so that the        registry.addendpoint ("/coordination") can be served through the WebSocket connection on the Web page. WITHSOCKJS ( );    }    @Override public    void Configuremessagebroker (messagebrokerregistry config) {        System.out.println ("Server started successfully") ;        The simple broker set here refers to the address that can be subscribed to, that is, the address that the server can send        /**         * userchat for user chat */        Config.enablesimplebroker ("/userchat");        Config.setapplicationdestinationprefixes ("/app");    }    @Override public    void Configureclientinboundchannel (Channelregistration channelregistration) {    }    @ Override public    void Configureclientoutboundchannel (Channelregistration channelregistration) {    }}

As you can see, these four methods must be implemented in a class. For the moment, just use the first two, so let me introduce the meaning of the code in the first two methods.

The first method, Registerstompendpoints, is to register the message connection point (my own understanding), so we have a connection point registration:
Registry.addendpoint ("/coordination"). WITHSOCKJS ();

We add a connection point called coordination, on the page we can use this link to the server and the WebSocket connection. But there is another sentence withsockjs, what is this? SOCKJS is a websocket communication JS Library, spring to this JS library for the background of automatic support, that is, if we use SOCKJS, then we do not need to do more configuration in the background, just add this sentence on it.

The second method, Configuremessagebroker, the main idea is to set the message agent, that is, the page with JS to subscribe to the address, but also our server to the WebSocket side to receive the JS end of the message sent to the address.
Config.enablesimplebroker ("/userchat"); Config.setapplicationdestinationprefixes ("/app");

First, define a connection point called Userchat, from the name can be seen out, and finally I will do a chat example. Then, set a prefix for the application access address, which is estimated to be separate from the other common requests. In other words, the address on the Web page to send a message to the server is/app/userchat.

Having said so many addresses, it is estimated that everyone is dizzy, because the whole prototype of the project has not come out, so it is chaotic. So the next step is to configure the JS side. The third step: Configure the browser end said so many addresses, estimated that everyone around dizzy, because the whole embryonic shape of the project has not come out, so very chaotic. So the next step is to configure the JS side. First we want to use two JS library, one is said before the SOCKJS, one is stomp, this is a communication protocol, temporarily do not introduce it, just need to know is a more convenient and more secure to send the message library on the line. WebSocket required to connect to the server:
var socket = new Sockjs ('/coordination '), var stompclient = stomp.over (socket), Stompclient.connect (",", Function ( frame) {});
Yes, only two sentences are needed. With these three words, we can already connect to the server. There is also a benefit of using SOCKJS, that is, the browser is compatible, if the IE11 below WebSocket support Bad browser, SOCKJS will automatically downgrade WebSocket to polling (this does not know can go to Baidu), before also said, spring on SOCKJS also supported, that is, if the WITHSOCKJS code was previously added, the server would automatically downgrade to polling. (What's the excitement, spring is so comfortable)

But the server is connected and nothing is done, so the next step is to write the response and data processing code on the server side.

To achieve the goal of this article, it is necessary to directly realize the function of chatting, and, on the basis of the chat function, and then realize the function of the cache chat record. The first step: the principle of chat implementation first, we need to clarify our needs. Usually, the chat on the Web page is the form of the chat room, so, this example also has a chat space concept, as long as in this space, you can chat together. Secondly, everyone can speak and be seen by others, so everyone will send their own content to the backstage, backstage to each person. On the client side, the socket can be easily implemented, and on the web, it was previously done by polling, but after the advent of websocket, it was possible to implement this function through a long connection, like a socket client, through WebSocket. The second step: the server base code through the above analysis of the principle can be known, the need to send to the background of the data is very simple, that is, user information, chat information, and space information, because it is a simple example, so the bean design is relatively simple:
public class Userchatcommand {    private String name;    Private String chatcontent;    Private String Coordinationid;    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    Public String getchatcontent () {        return chatcontent;    }    public void Setchatcontent (String chatcontent) {        this.chatcontent = chatcontent;    }    Public String Getcoordinationid () {        return coordinationid;    }    public void Setcoordinationid (String coordinationid) {        This.coordinationid = Coordinationid;    }    @Override public    String toString () {        return "userchatcommand{" +                "name= '" + name + ' \ ' +                ", Chatcont Ent= ' + chatcontent + ' \ ' + '                , coordinationid= ' + Coordinationid + ' \ ' + '                } ';}    

Through this bean to receive the message sent by the Web, and then forward on the server, the next is the logic of forwarding, but first need to introduce a spring websocket a annotation.

The annotation of the controller layer of spring MVC is requestmapping everybody knows, similarly, WebSocket also has the same function annotation, is messagemapping, its value is the access address. Now let's see how the controller layer is implemented:
    /**     * WebSocket Chat corresponding receive method and forwarding method     *     * @param userchat information about user chat *    /@MessageMapping ("/userchat") Public    void Userchat (Userchatcommand userchat) {        //Find address to send        String dest = "/userchat/chat" + Userchat.getcoordinationid ();        Send user's chat record        this.template.convertAndSend (dest, userchat);    }

Why is it so simple? Oh, can be so simple to implement the background code, all is the credit of spring. First of all, we agreed to send the rules of the address, that is, chat followed by the previous sent to the ID, and then through the "template" to forward, the "template" is a spring implementation of a Send template class: Simpmessagingtemplate, When we define a controller, we can inject it in the constructor method:

@Controllerpublic class Coordinationcontroller {    ...    Used to forward data (SendTo)    private simpmessagingtemplate template;    <pre name= "code" class= "java" >    @Autowired public    coordinationcontroller (Simpmessagingtemplate t) {        template = t;    }    .....}

Now the user sent over the chat message forwarded to a contractual space, as long as the web side of the user subscribed to the address of this space, then you will receive the JSON forwarded over. Now let's look at what the web side needs to do.

The third step: the Web-side code in an article has already introduced the connection WebSocket, so here does not repeat the said. First we create a page, write a textarea (id=chat_content) in the page to use as a chat record to display the place, write a input (id=chat_input) as a chat box, write a button as a Send button, although a bit humble, The beautification of the page is left behind when the feature is implemented. Now it's time to use the stompclient used in the previous article to connect to the background and define the stompclient as a global variable to make it easier for us to use it everywhere. According to logic, we first write a method of sending a message, so that we can first test whether the background is correct. We write a function called Sendname (which is random when writing code), and bind to the Send button onclick event. What we're going to do is probably the following steps: 1. Get input2. The data needed to assemble a string3. Send to the background the first step is simple, using jquery for a second, the second step can be done using the Json.stringify () method, The third step is to use the Stompclient send method, the Send method has three parameters, the first is to send the address, the second parameter is the header information, the third parameter is the message body, so sendname the overall code as follows:
Send Chat Message function sendname () {    var input = $ (' #chat_input ');    var inputvalue = Input.val ();    Input.val ("");    Stompclient.send ("/app/userchat", {}, json.stringify ({        ' name ': encodeURIComponent (name),        ' chatcontent ': encodeURIComponent (inputvalue),        ' Coordinationid ': Coordinationid    });}

Among them, name and Coordinationid are the corresponding user information, can be obtained through Ajax or JSP, there is not much to say.

Explain why the address is "/app/userchat": in the first article configured WebSocket information, one of which is applicationdestinationprefixes, configured "/app", from the name can be seen, is the WebSocket program address prefix, that is, in fact, this "/app" is to distinguish between ordinary address and websocket address, so long as the WebSocket address, you need to add "/app" in front of the controller address is "/ Userchat ", so the final form of the address is"/app/userchat ". Now run the program, in the background next breakpoint, we can see that the chat message has been sent to the background. But the web side does not show anything, this is because we have not subscribed to the corresponding address, so the background forwarding message is not to receive at all. Back to the previous function connected to the background: Stompclient.connect (",", "function (frame) {}), you can notice that the last is a method body, it is a callback method, when the connection is successful will call this method, So we subscribe to backstage messages in this method body. Stompclient's subscription method is called subscribe, there are two parameters, the first parameter is the address of the subscription, and the second parameter is the callback function when the message is received. Next, try subscribing to the chat message:

According to the previous convention, can get the address of the subscription is '/coordination/coordination ' + Coordinationid, so we subscribe to this address can be, when the subscription succeeds, as long as the background has a forwarding message, will call the second method, and, The body of the message passed in the background as a parameter. So the method of subscribing is as follows

        User Chat Subscription        stompclient.subscribe ('/userchat/chat ' + coordinationid, function (chat) {            showchat (Json.parse ( chat.body);        });

Convert the message body to JSON, and then write a method to display the chat information, the method of displaying the chat information is no longer explained, as follows:

Display chat information function showchat (message) {    var response = document.getElementById (' chat_content ');    Response.value + = decodeURIComponent (message.name) + ': ' + decodeuricomponent (message.chatcontent) + ' \ n ';}

Because before the processing of Chinese problems, so the data sent to the background is transcoded, from the background after the return, you also need to turn the code back.

Here, chat function has done, run the program, will find, really can chat! A chat program, that's that simple. But this does not satisfy, the function of the future can play our imagination to add, for example: I think, chat program, at least also to cache some chat records, not then come in the user do not know what the user is talking about, the user experience will be very bad, then look at the chat record cache is how to achieve it. Reprint: Http://blog.csdn.net/xjyzxx/article/details/38542665github Address: https://github.com/xjyaikj/OnlinePreparation

Go Spring WebSocket Tutorials

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.