WebSocket services under the Spring-boot framework

Source: Internet
Author: User

These days in the web to do real-time display service-side log file new features. To meet real-time needs, the solution I chose is to create a websocket link on the Web side with the server and send the new content to the Web side by the server via the Tail-f command.

For WebSocket Introduction, you can refer to this blog: http://www.cnblogs.com/lizhenghn/p/5155933.html (link only for learning communication, if there is a copyright issue please inform). What I want to introduce here is how to publish the WebSocket service under the Spring-boot framework.

First, publish WebSocket service on the service side

There are several ways to publish WebSocket services on the server side, including the servlet container scan initialization and spring scan initialization. I'm using the second way, you can define the WebSocket service as a separate class instance.

When the spring scan is initialized, you need to define a bean:serverendpointexporter to declare the server side. I put this bean in a separate WebSocket configuration class.

Import Org.springframework.context.annotation.bean;import org.springframework.context.annotation.Configuration; Import Org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configurationpublic class Websocketconfig {@Bean public serverendpointexporter Serverendpointexporter () {return new serverendpointexp      Orter (); }  }

The next step is to define the WebSocket service interface and use the keyword @ServerEndpoint ("/websocketpath") to declare an interface's access path.

import java.io.bufferedreader;import java.io.file;import java.io.ioexception;import  Java.io.inputstream;import java.io.inputstreamreader;import java.util.concurrent.copyonwritearrayset ; import javax.websocket.onclose;import javax.websocket.onerror;import javax.websocket.onmessage ;import javax.websocket.onopen;import javax.websocket.session;import  javax.websocket.server.serverendpoint;import org.springframework.stereotype.component;import  Org.springframework.web.bind.annotation.RestController, @ServerEndpoint ("/logwebsocket")    @Component   @RestControllerpublic  class LogWebSocketHandle {    private  session session;//each WebSocket session connection corresponds to a session    private static  copyonwritearrayset<logwebsockethandle> websocketset = new copyonwritearrayset< > (&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;/**&NBS);p;    *  the new WebSocket request opens.      *  OnOpen method is triggered after a new connection is established      *  @throws   jschexception      *  @throws  IOException       */     @OnOpen     public void onopen (session  session)  throws jschexception, ioexception {    this.session =  session;    websocketset.add (this);     //Server keeps session information, and returns the result to the client     //this statement is used by the server to send data to the client     session.getbasicremote (). SendText ( "Getting log <br>");           }     /**     * websocket request shutdown. The OnClose method is triggered when the      * websocket connection is closed      */      @OnClose &NBSP;&NBSP;&NBSP;&NBsp;public void onclose ()  {    websocketset.remove (this);                     }      @OnError     public void onerror (throwable thr)  {         thr.printstacktrace ();    }         /**    *  when a client sends a message, the server receives it through the OnMessage method      */     @OnMessage     public void onMessage  ( String message, session session)  throws IOException, JSchException,  Interruptedexception {          log.info ("Message from the client : " + message);                     try {            //process  message    //todo        } catch  ( Ioexception e)  {             E.printstacktrace ();        }//  bulk message to client   //         for  ( Session item : webSocketSet ) {   //                 Item.getbasicremote (). SendText (Message);  //        }       }         }

Second, the web side to establish a websocket connection

var websocket_host = window.location.host;//establishes WebSocket connection with the server var websocket = new WebSocket ("ws://" +websocket_host+ "/ Project name/logwebsocket ");//When the connection is established, the OnOpen method Websocket.onopen = function (event) {Console.log (" opened! ") is triggered; $ ("#chart_multiple div"). Append (Event.data);//Send data websocket.send (message) to the server;};/ /Receive server Data Websocket.onmessage = function (event) {$ ("#chart_multiple div"). Append (Event.data); $ ("#chart_multiple"). ScrollTop ($ ("#chart_multiple div"). Height ()-$ ("#chart_multiple"). Height ());



This article is from the "go it on the Road" blog, be sure to keep this source http://andrewli.blog.51cto.com/7625043/1965589

WebSocket services under the Spring-boot framework

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.