Spring boot websocket without stomp

Spring boot websocket without stomp DEFAULT

Spring Boot + WebSocket example without STOMP and SockJs

You can find many examples available on the web for spring websocket integration but most of them are using some messaging protocol like STOMP. Though Spring provides STOMP support out of the box but use of any messaging protocol to connect to websocket is not mandatory. You can use raw websocket by defining your own messaging protocol to connect to spring websocket using TextWebSocketHandler. In this post we will be creating a websocket connection using Spring but without STOMP and SockJs.

If you are looking for spring websocket example with STOMP and Spring Security, then visit here spring websocket example with STOMP or else here is an example of Spring boot websocket angular example

What is STOMP

STOMP stands for Streaming Text Oriented Messaging Protocol. As per wiki, STOMP is a simple text-based protocol, designed for working with message-oriented middleware (MOM). It provides an interoperable wire format that allows STOMP clients to talk with any message broker supporting the protocol.

This means when we do not have STOMP as a client, the message sent lacks of information to make Spring route it to a specific message handler method. So, if we could create a mechanism that can make Spring to route to a specific message handler then probably we can make websocket connection without STOMP.

Custom WebSocketHandler

We concluded that if we do not want to use STOMP, then we have to define our custom message protocol handler that should handle all the messages coming from any websocket client. Before defining any custom message handler class, we need to identify what format of message our handler class expect from the client. It can be either XML or Json or of any other format.

In this example we assume that the websocket client will be communicating with the server in JSON. Hence our handler will be a JSON message handler and we can define this in Spring by extending TextWebSocketHandler.java


TextWebSocketHandler is a class in Spring library that extends AbstractWebSockethandler class and primarily meant for handling only text messages. So, if you are expecting any binary messages from your websocket client then defining your custom handler class by extending TextWebSocketHandler is of no use as binary messages will be rejected with CloseStatus.NOT_ACCEPTABLE.

Implementation of Spring Websocket without STOMP

While coming to the code implementation, we will be creating a simple web app using Spring websocket where message transfer between the client and server will happen via websocket without STOMP. Let us start by defining our project structure.

Project Structure


Maven Dependency

pom.xml <properties> <tomcat.version>8.0.3</tomcat.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </dependencies>

Server Side Implementation

Let us start by defining .

@SpringBootApplication: This is a convenience annotation that is equivalent to declaring , and .

Application.javapackage com.devglan.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplicationpublic class Application extends SpringBootServletInitializer { private static Class

Overriding TextWebSocketHandler

Now let us define our custom handler class by extending that will override the protocol to handle the text message. Our handler will be capable of handling Json message. This class records all the session once any websocket connection is established and broadcasts the message to all the sessions once any message is received.

Instead of broadcasting message to all the clients, you can also configure to send message to a particular session. This configuration is also explained in coming section.

SocketHandler.classpackage com.devglan.config; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; @Componentpublic class SocketHandler extends TextWebSocketHandler { ListOther Interesting PostsMaintaining Spring Session during Websocket ConnectionSpring Boot Websocket Example with STOMPSpring Boot JMS ActiveMQ ExampleSpring Boot ActuatorSpring Boot Spring MVC ExampleSpring Boot Security Password Encoding using Bcrypt Encoder

Spring Web Socket Configurations

Now let us define our websocket configurations. The below configuration will register websocket handler at and define our custom handler class that will handle all the messages from the websocket client.

WebSocketConfig.classpackage com.devglan.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @[email protected] class WebSocketConfig implements WebSocketConfigurer { public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new SocketHandler(), "/name"); } }

This is it for server side. Now let's jump to client side code.


Here we have defined 3 methods each for creating websocket connection when user clicks on connect button, sending message to the server once send button is clicked and another for listening the server response that will come from the server.

function connect() { ws = new WebSocket('ws://localhost:8080/name'); ws.onmessage = function(data){ showGreeting(data.data); } setConnected(true); } function disconnect() { if (ws != null) { ws.close(); } setConnected(false); console.log("Disconnected"); } function sendName() { ws.send($("#name").val()); } function showGreeting(message) { $("#greetings").append(" " + message + ""); }

Run Application

1. Run Application.java as a java application and the main method will execute.

2. In the browser make request at http:localhost:8080.

3. Create websocket connection by clicking connect button and enter the name and click on send.

4. The handler class at server side will handle the message and return the greeting message as a response which will be shown in the browser as below:


Sending Message to Single Session

Above implementation will broadcast message to all the sessions and hence all the client will receive the messaage at a time. To send message to a single client we need to tweak our as below. SocketHandler.java

package com.devglan.config; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; @Componentpublic class SocketHandler extends TextWebSocketHandler { List

This change in SocketHandler.java will ensure that the message is sent to a single session.


I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download the source

Sours: https://www.devglan.com/

Spring Boot + WebSocket Basic Example

WebSocket vs HTTP

WebSocket is a computer communications protocol, for two or more computers to communicate with each other at the same time (full-duplex) over a single TCP connection. Here some differences between HTTP (the most common protocol used for internet applications) and WebSocket:

HTTPWeb Socket
Messaging PatternUnidirectional, client always initiates the request and server responseBi-directional, either client or server can initiate sending a message
DuplexHalf, response occur after requestFull, client/server communication are independent
Service PushNot natively supported. Client polling or streaming download techniques usedCore feature
ConnectionsMultiple TCP connections. For each request/response a new TCP session is neededSingle TCP connection. After initial connection using HTTP, the connection then upgraded to a socket based connection and used for all the future communication
OverheadModerate overhead per request/connectionModerate overhead to establish & maintain the connection, then minimal overhead per message
CachingSupported. HTTP supports caching so that content can be stored locally by the browser and reused when required.Not possible. Don't fit in the necessary scheme for caching, e.g. one requests which results in the same response every time
Supported clientsBroad supportModern languages & clients

This article about Spring Boot and WebSocket means to be part of a series. In this post, we will learn to create a basic WebSocket application. The example in this article is a simple web application that broadcast messages using plain WebSocket connection.

Let's start by creating a new Spring Boot application.

Creating Spring Boot Application

Generate Spring Boot application we can use (https://start.spring.io/ ) or . For this tutorial, add WebSocket dependency:


Create Project in https://start.spring.io/

More dependencies needed to complete the application:

  • Thymeleaf
  • Webjars (Bootstrap and jQuery)
  • Lombok

Since we are using maven, here for this project:


Spring Boot Application

is the main entry point of our Spring Boot application:


Creating WebSocket Handler

In Spring we can create a customized handler by extends abstract class or one of it's subclass, either or :

  • TextWebSocketHandler
    Base class for implementations that process text messages only.
  • BinaryWebSocketHandler
    Base class for implementations that process binary messages only.

For our sample, since we need to handle only text so our class will extends .


Spring Web Socket Configuration

For Spring application to forward client requests to the endpoint , we need to register the handler. Class is a customized configuration class that implements interface . interface defines callback methods to configure the WebSocket request handling (example: adding WebSocket handler) via annotation.


Controller and HTML Template

Next, we create the UI part for establishing WebSocket and making the calls. Define the as follow:


Function returning the name of Thymeleaf template that will be used to render the response. The template that will be rendered in this function is . Please refer to Adding Controller in Spring Boot + Thymeleaf CRUD Example.


We are using and from Thymeleaf's page layout, and Webjars. We will not talk about these things in this article. For completeness of the example, here the content of :


Run Application

We can run our application from IDE, or from terminal. From terminal, go to the project’s root directory and run:

$ mvn spring-boot:run

It'll run the main method in class. Open browser and make request at http://localhost:8080/websocket.



Create WebSocket connection by clicking "Connect" button. Here the request headers when make connection (truncated - with unnecessary information removed).

Host: localhost:8080 Origin: http://localhost:8080 Sec-WebSocket-Version: 13 Sec-WebSocket-Extensions: permessage-deflate Sec-WebSocket-Key: PSfHzxFfZC1KVUUuC1fQHg== Connection: keep-alive, Upgrade Upgrade: websocket

And here response headers (also truncated)

HTTP/1.1 101 Upgrade: websocket Connection: upgrade, keep-alive Sec-WebSocket-Accept: to0bX/YSZHbE/Rtp2OOo5qXpR7I= Sec-WebSocket-Extensions: permessage-deflate

After that, we can start broadcast the message. You can open multiple session of

connect and broadcast message

connect and broadcast message

On clicking "Disconnect" the WebSocket connection will be closed.

Sours: https://www.dariawan.com/tutorials/spring/spring-boot-websocket-basic-example/
  1. Austin hotels with lazy river
  2. 1978 ford f150 dash pad
  3. Know your worth tattoo ideas
  4. Fall for you shanice lyrics
  5. Sony tv casting not working

In this brief post, let’s see how we can implement a simple web socket client for a non-stomp based websocket service.

In this example, we will be implementing the client for the demo echo test websocket service.


<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.idodevjobs</groupId> <artifactId>spring-websocket-without-stomp-client-example</artifactId> <version>1.0-SNAPSHOT</version> <name>spring-websocket-without-stomp-client-example</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> </dependencies> </project>

We have inherited the spring-boot-starter-parent pom and added the only dependency spring-boot-starter-websocket which will bring in all the required dependencies.


package com.idodevjobs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main( String[] args ) { SpringApplication.run(App.class, args); } }

A pretty straight forward spring boot start-up class.


package com.idodevjobs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHttpHeaders; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.client.WebSocketClient; import org.springframework.web.socket.client.standard.StandardWebSocketClient; import org.springframework.web.socket.handler.TextWebSocketHandler; import javax.annotation.PostConstruct; import java.net.URI; import java.util.concurrent.TimeUnit; import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; @Service public class SpringWebsocketWithoutStompClient { private static final Logger LOGGER = LoggerFactory.getLogger(SpringWebsocketWithoutStompClient.class); @PostConstruct public void connect() { try { WebSocketClient webSocketClient = new StandardWebSocketClient(); WebSocketSession webSocketSession = webSocketClient.doHandshake(new TextWebSocketHandler() { @Override public void handleTextMessage(WebSocketSession session, TextMessage message) { LOGGER.info("received message - " + message.getPayload()); } @Override public void afterConnectionEstablished(WebSocketSession session) { LOGGER.info("established connection - " + session); } }, new WebSocketHttpHeaders(), URI.create("ws://echo.websocket.org")).get(); newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> { try { TextMessage message = new TextMessage("Hello !!"); webSocketSession.sendMessage(message); LOGGER.info("sent message - " + message.getPayload()); } catch (Exception e) { LOGGER.error("Exception while sending a message", e); } }, 1, 10, TimeUnit.SECONDS); } catch (Exception e) { LOGGER.error("Exception while accessing websockets", e); } } }

In this simple service class, we have a void method and configured it to get executed once the bean gets initiated.

There are 3 important things to pay attention to –

  • StandardWebSocketClient
  • An instance of StandardWebSocketClient – the basic WebSocketClient based on Java Websocket API.

  • TextWebSocketHandler
  • An anonymous extension of TextWebSocketHandler where we have overridden event handlers – handleTextMessage and afterConnectionEstablished to log the messages.

  • ScheduledExecutorService
  • A scheduler to send a message to the existing websocket connection at a regular interval of 10 seconds.

Running the App.java class will start the application and once SpringWebsocketWithoutStompClient gets instantiated, we can see the logs about websocket connection, send and receive messages.


2019-02-06 20:06:23.678 INFO 670 --- [cTaskExecutor-1] c.i.SpringWebsocketWithoutStompClient : established connection - StandardWebSocketSession[id=20372fd5-304f-7a23-a61c-47009d0aacbb, uri=null]
2019-02-06 20:06:23.958 INFO 670 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-02-06 20:06:24.285 INFO 670 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-02-06 20:06:24.295 INFO 670 --- [ main] com.idodevjobs.App : Started App in 4.842 seconds (JVM running for 5.507)
2019-02-06 20:06:24.702 INFO 670 --- [pool-1-thread-1] c.i.SpringWebsocketWithoutStompClient : sent message - Hello !!
2019-02-06 20:06:24.751 INFO 670 --- [lient-AsyncIO-1] c.i.SpringWebsocketWithoutStompClient : received message - Hello !!

Like this:



This entry was posted in java and tagged java, spring, spring-boot, spring-boot-websocket, stomp. Bookmark the permalink.

Sours: https://idodevjobs.wordpress.com/2019/02/07/spring-websocket-client-without-stomp-example/
How to Use WebSockets with Java - Spring Boot

Dima: Don't thank. I had no idea that he could come to this, although I knew that he was bad. I wish I could come back and finish it off !!. "Olya:" Calm down. Everything is all right.

Without websocket spring stomp boot

I asked stupidly. - Well, then. And here - your Lena, she walks so beautiful, she always smells nice, legs in pantyhose - and not in pants. - I noticed. - Yes, I tried, - he sighed bitterly, - she - she doesn't want to hear anything.

Spring Boot + WebSocket Hello World Example

Not bad for a start, then. the girl said with interest. Married people will not know about you yet, we can, for a while, sleep in one bed without any problems. And then we will tell them everything, everyone will be just happy that we are not in a hurry to get married, and they will like you even more.


You will also be interested:

Her thoughts were in the field of History. She was very fond of this subject, and she was especially interested in the monarchical history of Britain. The girl admired the culture of this country.

1390 1391 1392 1393 1394