dir.by  
Programming, development, testing
Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
Creating a new Spring WebSocket application (Java WebSocket sends a message to the JavaScript WebSocket) | Java, Spring WebSocket, Spring Boot, Maven
  Looked at 1639 times    
 Creating a new Spring WebSocket application (Java WebSocket sends a message to the JavaScript WebSocket) | Java, Spring WebSocket, Spring Boot, Maven 
last updated: 20 April 2025
Download an example:
MySpringWebSocket.zip ...
size: 22 kb
 
Note! You must have Java JDK installed. If you don't have it, then need to download and install Java JDK ...

Note! You must have IntelliJ IDEA Ultimate installed. If you don't have it, then need to download and install IntelliJ IDEA Ultimate ...

Note! You must have Tomcat Web Server installed. If you don't have it, then need to download and install Tomcat Web Server ...
Step 1. Create a new project with the type Spring Boot
 
Select Spring Boots:
 
Since we have a simple project, do not check the boxes:
 
The project was created:
Step 2. Add the spring-boot-starter-web and spring-websocket libraries to the pom.xml file

spring-boot-starter-web library is essential for running our application as a web server.
spring-websocket library with web socket functions.
<?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>
     <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>3.4.4</version>
          <relativePath/> <!-- lookup parent from repository -->
     </parent>
     <groupId>org.example</groupId>
     <artifactId>MySpringWebSocket</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <name>MySpringWebSocket</name>
     <description>MySpringWebSocket</description>
     <url/>
     <licenses>
          <license/>
     </licenses>
     <developers>
          <developer/>
     </developers>
     <scm>
          <connection/>
          <developerConnection/>
          <tag/>
          <url/>
     </scm>
     <properties>
          <java.version>17</java.version>
     </properties>
     <dependencies>
          <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter</artifactId>
          </dependency>

          <!-- web starter -->
          <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
          </dependency>


          <!-- web socket -->
          <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-websocket</artifactId>
          </dependency>


          <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-test</artifactId>
               <scope>test</scope>
          </dependency>
     </dependencies>

     <build>
          <plugins>
               <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
               </plugin>
          </plugins>
     </build>

</project>
Attention!
If plugin Spring-Websocket is not set, then you need to set Spring-Websocket plugin to Intellij Idea ...



Step 3. Create a new MyWebSocketHandler.java file
Right-click on my package folder and create a new java file
 
Let's write the name MyWebSocketHandler
And choose the type Class
Press Enter
The file was created.
 
Inside the MyWebSocketHandler.java file, add the code:
  Java  
package org.example.myspringwebsocket;

import java.io.IOException;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

     @Override
     public void handleTextMessage(WebSocketSession session, TextMessage message)
               throws InterruptedException, IOException {

          String payload = message.getPayload();
          session.sendMessage(new TextMessage("Today weather is good"));
     }
}
Step 4. Create a new MyWebSocketConfig.java file
Right-click on my package folder and create a new java file
 
Let's write the name MyWebSocketConfig
And choose the type Class
Press Enter
The file was created.
 
Inside the MyWebSocketConfig.java file, add the code:
package org.example.myspringwebsocket;

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;

@Configuration
@EnableWebSocket
public class MyWebSocketConfig implements WebSocketConfigurer {

     public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
          registry.addHandler(new MyWebSocketHandler(), "/mysocket1").setAllowedOrigins("*");
     }

}
Step 5. Launch the project and see how it works
 
We see that our application is running:
1) Spring Boot is initialized when our application is launched (because we built our application with the Spring Boot type)
2) Next, Tomcat web server with port 8080 is started (because <dependency> ... spring-boot-starter-web ... </dependency> was added to the pom.xml file)
 
Our web server is running, here is its address:
http://localhost:8080

Since we started the program, the web server created a web socket.
To check, create a new file D:/1.html on your disk
  Html  
<script>
     webSocket = new WebSocket('ws://localhost:8080/mysocket1'); // connect to server

     webSocket.onopen = function(event) {
          alert("Connection open");

          webSocket.send("My name is Evgen"); // send message to server
     };

     webSocket.onmessage = function(event) {
          alert("message from server: " + event.data); // message from server
     };
</script>
Let's run this file 1.html and see:
 
← Previous topic
Create a new Spring Web application (the request goes to the Controller → Controller creates a response as text or json) | Java, Spring Web, Spring Boot, Maven
 
Next topic →
Create Azure Web App with the type Java (free). That is, create an empty web server
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Экскурсии по Москве Экскурсии по Москве: пешеходные, автобусные и речные прогулки на любой вкус
  Объявления  
  Объявления  
 
Download and install
Installation JDK (download and install the Java library for Windows)
Download and install IntelliJ IDEA to explore Java, Spring, Jakarta EE | Functionality and differences: Community | Ultimate
Learn the language Java (class, interface, properties, etc.)
Create a simple console app in IntelliJ IDEA to learn Java
What is interface in Java ?
Directly in the code (at runtime) we make an implementation for the interface | Java
Threads in Java
lambda is an unnamed method (no name and no class owned) | Java
Exceptions and handling in Java. Example: try {...} catch (Exception e) {...}
Why use throws Exception in the function name in Java? Answer: The method throws an exception and there is no handling of try catch. Example: float CalculateDensity(float mass, float volume) throws Exception { ... throw new Exception("Error! Volume is zero."); ... }
Java web application (servlet, jsp page, basic functionality and no frameworks)
Creating a new simple web application (jsp web page) | Java, Maven
Create a web servlet (the servlet is located on the web server, returns the result on request) | Java
Installation Tomcat web server (download and install for Windows)
Check, test Tomcat web server (create a new my.hml file)
What is Maven
What is a dynamic web page jsp (Java Server Page) ?
How to install Smart Tomcat plugin in Intellij Idea
Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
What is Spring? Why use Spring in Java?
What is Spring Bean? What is Spring Container? IoC (inversion of control) | Creating a simple Spring project and configuration Spring Container in an XML file | Editor IntelliJ Idea and language Java
What is Dependency Injection in Spring? Creating a simple Spring project with Dependency Injection in the constructor with the attributes @Component, @Autowired | Editor IntelliJ Idea and language Java
Create a new Spring Web application (the request goes to the Controller → Controller creates a response as text or json) | Java, Spring Web, Spring Boot, Maven
Creating a new Spring WebSocket application (Java WebSocket sends a message to the JavaScript WebSocket) | Java, Spring WebSocket, Spring Boot, Maven
Create Azure Web App with the type Java (free). That is, create an empty web server
Put the Java Spring web application in Azure
Connect to the application Azure Web App (Java) via FTP | use File Explorer
Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java, Spring Boot
How to install Spring WebSocket plugin in Intellij Idea
Jakarta EE / Java EE in Java (Web Applications, Web Services)
What is Jakarta EE (Java EE)? | In which editor (program) is it convenient to write Jakarta EE (Java EE) code?
Creating a simple web project in IntelliJ Idea Ultimate | Jakarta EE (Java EE)
Struts in Java (extends API Java Servlet using MVC)
What is Struts | Java
Interviews on Java

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика