WebSocket implementation with Spring Boot

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Spring Boot is a microservice-based Java framework used to create web application. It provides radically faster and widely accessible getting-started experience for the development along with ready to use non functional features. It is licensed under Apache License 2.0.

WebSocket

The WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.

It will be persistent connection to send and receive messages quickly between client and server without much overhead.It can be used for Chat Applications, Long Polling Applications, Multi-player Game Applications, Send live Analytics data.

Getting Started

In this article we will create a spring boot application using Maven and send some sample messages from client and server and receive vice versa. Create pom.xml with following dependencies inside the project dir

      mkdir springwebsocket
      cd springwebocket

 

In the pom.xml, we need to keep spring boot starter parent to create a spring boot project. We would require spring boot starter web for having the http endpoints. It will initially do a handshake on the http endpoints and then web socket protocol is used for future communications. Websocket related dependency are also added for sending and receiving the message in the back end.

Also spring boot maven plugin to make compile and executable jar.

 

  <?xml version="1.0" encoding="UTF-8"?>
  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.nagappan</groupId>
  <artifactId>springwebsocket</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
   </parent>
   <licenses>
        <license/>
   </licenses>
   <!-- Additional lines to be added here... -->
   <dependencies>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
       <dependency>
            <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-websocket</artifactId>
       </dependency>
    </dependencies>
    <!-- Package as an executable jar -->
   <build>
      <plugins>
          <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
       </plugins>
  </build>
</project>

Now we will create the spring boot application starter in the main class using SpringApplication.run(classname). This will create the spring web context with the tomcat as embedded server container.

  @RestController
  @EnableAutoConfiguration
  @ComponentScan(basePackages= {"com.nagappan.springwebsocket"})
  public class SpringWebsocket {

      @RequestMapping("/")
      public String home() {
          return "hello world";
      }

      public static void main(String args[]) {
         SpringApplication.run(SpringWebsocket.class, args);
      }
}


Component package scan has been added for the configuration of those packages automatically. We will now create websocket endpoint ("/my-websocket-endpoint") and register handler for the endpoint with websockethandler registry. The handler should be a sub class extended from WebSocketHandler.

   @Configuration
   @EnableWebSocket
   public class WebSocketConfiguration implements WebSocketConfigurer {

      @Bean
      public WebSocketHandler myMessageHandler() {
           return new MyMessageHandler();
      }

      @Override
      public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
           System.out.println("websocket endpoint handler");
           registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");
      }

  }

The MyMessageHandler is responsible to send and receive text messages so we need to extend the handler from TextWebSocketHandler which has listeners for Connection establishment, Closing connections and Handling text messages. Once the connection is established it sends a message to client "You are now connected to the server. This is the first message".

   public class MyMessageHandler extends TextWebSocketHandler {

      @Override
      public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
           
          System.out.println("web socket has been closed");
      }

     @Override
     public void afterConnectionEstablished(WebSocketSession session) throws Exception {
           /* The WebSocket has been opened
          I might save this session object so that I can send messages to it outside of this method
          Let's send the first message */
         System.out.println("web socket connection established");
         session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
         
        System.out.println("Message received: " + textMessage.getPayload());
    }

}

Client can now connect to websocket with WebSocket Javascript API. Javascript websocket API has event handlers for socket open and message handler. Create a websocket and connect to the websocket endpoint (/my-websocket-endpoint). On the successful socket open handler, send the message to the server through websocket. On successful receive server's message(socket.onmessage handler)and provides support to send message to the server. In this example, an input field is provided where user enters the message which will received by the server and it sends back the message to the client. Those discussion conversion will be displayed in the server message in the label fields.

   <!DOCTYPE html>
   <html lang="en">
   <head>
   <meta charset="UTF-8">
   <title>Spring web socket tutorial</title>
   <script>
       var socket = new WebSocket('ws://' + window.location.host + '/my-websocket-endpoint');

       <!-- Add an event listener for when a connection is open -->
      socket.onopen = function() {

          console.log('WebSocket connection opened. Ready to send messages.');

         <!-- Send a message to the server -->

        socket.send('Hello, from WebSocket client!');

      };

      <!-- Add an event listener for when a message is received from the server -->
      socket.onmessage = function(message) {
           console.log('Message received from server: ');
           console.log(message);
           document.getElementById("displaymsg").innerText += "\n" + message.data;
     };

     function sendbtn() {
          let textmsg = document.getElementById("msgtext").value;
          console.log("goint to send message");
          console.log(textmsg);
          socket.send(textmsg);
    }

  </script>
  </head>
  <body>
     <input id="msgtext" type="text"></input>
     <button onclick="sendbtn()">Send</button>

     <h1>Messages received from server</h1>
     <div style="border-style: solid; border-width: 2px;">
            <label id="displaymsg"></label>
     </div>
   </body>
  </html>


Start the application using "mvn spring-boot:run". Then web client ui show all the message send to server in the below label html element.

 

Websocket implementation using spring boot

 

Reference:

Source code : https://github.com/nagappan080810/springwebsockets


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Thymeleaf - Text display, Iteration and Conditionals

  • thymeleaf template-engine web-programming java

Thymeleaf is a server-side Java template engine for both web and standalone environments. It is a better alternative to JavaServer Pages (JSP). Spring MVC and Thymeleaf compliment each other if chosen for web application development. In this article, we will discuss how to use Thymeleaf.

Read More


JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


Activiti - Open Source Business Automation

  • business-automation business bpm

Activiti Cloud is the first Cloud Native BPM framework built to provide a scalable and transparent solution for BPM implementations in cloud environments. The BPM discipline was created to provide a better understanding of how organisations do their work and how this work can be improved in an iterative fashion.

Read More


Struts 1.x End Of Life. Whats alternative?

  • java eol struts

The Apache Struts Project Team announced End of Life (EOL) for Struts 1.x web framework. Struts was launched in the year 2000. It is only of the widely used web framework. It gave better control over writing UI and business logic code directly in to JSPs.

Read More



Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


Ngnix - High Performance Web Server, Proxy Server, Content Cache and Reverse Proxy

  • load-balancer proxy-server web-server

Nginx is a High Performance Web Server, Proxy Server, Content Cache and Reverse Proxy server. It can also be used as mail proxy server and a generic TCP/UDP proxy server. Nginx claims to be more efficient and faster in the Web space compared to the other web servers. This can be evident with the architecture which is based on asynchronous event-driven approach. The event driven architecture enables to scale to hundreds / thousands of concurrent connections.

Read More


8 Best Open Source Searchengines built on top of Lucene

  • lucene solr searchengine elasticsearch

Lucene is most powerful and widely used Search engine. Here is the list of 7 search engines which is built on top of Lucene. You could imagine how powerful they are.

Read More


LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More


RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More


JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More


ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More


Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More


MailHog - Web and API based SMTP testing

  • smtp-testing testing-tool smtp test automation email-server email

Most of the projects will have a requirement of sending and receiving mails. We have mentioned about GreenMail - Email Test Framework, in our previous article about API based SMTP testing. In this article, we discuss about MailHog - Web and API based SMTP testing. You send out a mail from your code and you can check it via web visually and also via API. Those who do API testing can check via API. Developers may want to visually verify the format of the mail. MailHog is a best bet for SMTP testing.

Read More


RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More


Lucene Vs Solr

  • searchengine lucene solr

Lucene is a search library built in Java. Solr is a web application built on top of Lucene. Certainly Solr = Lucene + Added features. Often there would a question, when to choose Solr and when to choose Lucene.

Read More


RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More


8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More


How to contribute to open source

  • opensource contribute participate foss

I could see many many students posting this question in many forums, I want to contribute to open source but How to contribute? There are many ways to do that. I have listed a few and I hope it might be useful.

Read More


How to create SEO friendly url

  • seo url searchengine

SEO friendly URL is recommended for any website which wants to be indexed and wants its presence in search results. Searchengine mostly index the static URL. It will avoid the URL which has lot of query strings. Almost all websites generate content dynamically then how could the URL be static. That is the job of the programmer.

Read More