Simple websocket demo


There are two ways to use websocket: one is to use sockjs, and the other is to use H5 standard. The use of HTML5 standard is naturally more convenient and simple, so the use method matched with H5 is recorded.

  1. pom

  2. Create a websocket endpoint using @ serverendpoint
    First, inject the serverendpointexporter. This bean will automatically register the websocket endpoint declared with the @ serverendpoint annotation. Note that if you use a separate servlet container instead of directly using the spring boot built-in container, do not inject the server endpoint exporter, as it will be provided and managed by the container itself.

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

    The next step is to write the specific implementation class of websocket, and directly the code:

    public class MyWebSocket {
     //The connection session with a client needs to send data to the client through it
     private Session session;
     //The thread safe set of the concurrent package is used to store the mywebsocket object corresponding to each client.
     private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
     public void onOpen(Session session){
         this.session = session;
         System. Out. Println ("create connection: section" + websocketset. Size());
     public void onClose(){
         System.out.println ("close connection");
     public void onMessage(String message){
         System. Out. Println ("accept client message:" + message);
      *Mass messaging
     public void sendMessage(String message){
         for (MyWebSocket myWebSocket : webSocketSet){
             try {
             } catch (IOException e) {
     //A single message can be transformed on the basis of mass sending

    The only difference between using springboot and using the @ component declaration is that the websocket is managed by the container itself, but even the container is managed by spring in springboot.
    Although @ component is singleton mode by default, springboot will initialize a bean for each websocket connection, so it can be saved with a static set.

  3. Front end code

    <!DOCTYPE html>
    <html xmlns:th="">
     <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     < title > Home Page < / Title >
    <script type="text/javascript" th:inline="javascript">
     var websocket = null;
     if('WebSocket' in window){
         // is the project request address. Websocket is the corresponding value in @ serverendpoint ("/ websocket"). Together, it is the request websocket address
         websocket = new WebSocket('ws://');
         Alert ("this browser does not support websocket!")
     websocket.onopen = function (event) {
         Console.log ("establish connection");
     websocket.onclose = function (event) {
         Console.log ("close connection");
     websocket.onmessage = function (event) {
         Console.log ("accept message:" + event. Data);
         //Simulate sending information to the server
         Websocket. Send ("I have received the message!")
     websocket.onerror = function (event) {
         Console.log ("an error occurred")
     window.onbeforeunload = function () {
  4. test method

    public class TestWebSocketSendController {
     private MyWebSocket myWebSocket;
     public String send(@RequestParam("message") String message){
         //Todo other business
         //Websocket service
         Return "success";

    Open master page127.0.0.1:8080/index.html
    Simple websocket demo
    Browser request127.0.0.1:8080/testWebSocketSend/se…The controller address I wrote before
    Simple websocket demo
    The server accepts the message printing of the client
    Simple websocket demo

This work adoptsCC agreement, reprint must indicate the author and the link to this article