An example of integrating websocket with springboot



We all know that the HTTP protocol can only send a request to the server unilaterally to get a response, and the server cannot actively push messages to the browser. There are two main ways to implement browser active push:

  • Polling: there are many disadvantages, but the implementation is simple
  • Websocket: establish TCP connection between browser and server to realize full duplex communication

Spring boot uses websocket in two ways, one is to implement simple websocket, the other is to implement stomp protocol. This article implements a simple websocket, which is next in stomp.

Note: the following are for using the springboot built-in container

Two, implementation

1. Dependency introduction

The key to use websocket is the @ serverendpoint annotation, which is the annotation in the Java EE standard. Tomcat7 and above have been implemented. If you use the traditional method to deploy the war package to tomcat, you only need to introduce the following Java EE standard dependency:


If the built-in container of springboot is used, there is no need to introduce it. Springboot has already been included. We just need to introduce the following dependencies:


2. Inject bean

First, inject a serverendpoint exporter bean, which will automatically register websocket endpoint declared with @ serverendpoint annotation. The code is as follows:

public class WebSocketConfig {
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();

3. Declare endpoint

Create class, and process websocket logic in this class

@Serverendpoint (value = "/ websocket") // accept websocket request path
@Component // register in spring container
public class MyWebSocket {
//Save all online socket connections
private static Map<String,MyWebSocket> webSocketMap = new LinkedHashMap<>();
//Record the current number of Online
private static int count=0;
//Current connection (each websocket connection will create a mywebsocket instance
private Session session;
private Logger log = LoggerFactory.getLogger(this.getClass());
//Handle connection establishment
public void onOpen(Session session){
addCount(); ("new connection join: {}", session. Getid());
//Accept message
public void onMessage(String message,Session session){ ("received client {} message: {}", session. Getid(), message);
This. SendMessage ("received message:" + message);
}catch (Exception e){
//Handling errors
public void onError(Throwable error,Session session){ ("error {}, {}", session. Getid(), error. Getmessage());
//Process connection closure
public void onClose(){
reduceCount(); ("connection closing: {}", this. Session. Getid());
//Mass message
//Send message
public void sendMessage(String message) throws IOException {
//Broadcast message
public static void broadcast(){
V. SendMessage ("this is a test broadcast");
}catch (Exception e){
//Get the number of online connections
public static int getCount(){
return count;
//Operation count, use synchronized to ensure thread safety
public static synchronized void addCount(){
public static synchronized void reduceCount(){

4. Customer realization

The client uses H5 native websocket, which may not be supported by some browsers. The code is as follows:

< title > websocket test < / Title >
<meta charset="utf-8" />
< button onclick = "sendmessage()" > test < / button >
let socket = new WebSocket("ws://localhost:8080/websocket");
socket.onerror = err => {
socket.onopen = event => {
socket.onmessage = mess => {
socket.onclose = () => {
Console.log ("connection closed");
function sendMessage() {
If (socket. ReadyState = = = 1) socket. Send ("this is a test data");
Else alert ("websocket connection has not been established");

Three, test

Set up a controller to test mass distribution, the code is as follows:

public class HomeController {
public void broadcast(){

Then open the HTML above, and you can see that both the browser and the server output the successful connection information:

Event {isTrusted: true, type: "open", target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …}
2018-08-01 14:05:34.727 info 12708 -- [nio-8080-exec-1] com.fxb.h5websocket.mywebsocket: new connection joining: 0

Click the test button to see the following output on the server:

2018-08-01 15:00:34.644 info 12708 -- [nio-8080-exec-6] com.fxb.h5websocket.mywebsocket: receive client 2 message: This is a test data

Open the HTML page again, so that there are two websocket clients, and then access the localhost: 8080 / broadcast in the browser to test the group sending function. Each client will output the following information:

Messageevent {istrusted: true, data: "this is a test broadcast", origin: "WS: // localhost: 8080", lasteventid: "", source: null }

Source code can be downloaded from GitHub

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.