JS client calls WebSocket server, based on Springboot

Catalog

WebSocket server

Simply speaking, WebSocket itself is a stateful two-way communication protocol based on TCP, which can realize instant communication, message push and other business scenarios requiring long connection.

Create spring boot project and introduce WebSocket dependency

The pom dependencies introduced in this example are as follows:

<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>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Configure WebSocketConfig

The code is as follows

package com.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * WebSocket Configuration class
 * @author Neo
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){

        return new ServerEndpointExporter();

    }
}

Configure WebSocketServer

The code is as follows

package com.websocket.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WebSocket Service class
 * @author Neo
 */
@Slf4j
@ServerEndpoint(value = "/ws/server")
@Component
public class WebSocketServer {

    //A thread safe collection of session information for each client
    private static final CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<>();
    //Use thread safe counters to record online numbers
    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * Method called on successful connection
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        //Store session information
        sessions.add(session);
        //Count +1
        int cnt = onlineCount.incrementAndGet();
        //Print log
        log.info("There are connections to join. The current number of connections is:", cnt);
        //Send message to client
        this.sendMessage(session, "Successful connection");
    }

    /**
     * Method called when connection is closed
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        //Delete session information
        sessions.remove(session);
        //Count -1
        int cnt = onlineCount.decrementAndGet();
        //Print log
        log.info("There are connections closed. The current number of connections is:", cnt);
    }

    /**
     * Method called when a client message is received
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        //Print log
        log.info("Message from client:",message);
        //Send message to client
        this.sendMessage(session, "Received message, message content:"+message);
    }

    /**
     * Method called on exception
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        //Print log
        log.error("An error occurred: Session ID: ",error.getMessage(),session.getId());
    }

    /**
     * send message
     * @param session
     * @param message
     */
    public void sendMessage(Session session, String message) {
        try {
            //send message
            session.getBasicRemote().sendText("SID:::" + session.getId() + ":::" + message);
        } catch (IOException e) {
            //Print log
            log.error("Error sending message:", e.getMessage());
        }
    }

    /**
     * Mass message
     * This method can be upgraded to a message push tool, playing an advertisement or something to the online client
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        for (Session session : sessions) {
            //Determine if the connection is open
            if(session.isOpen()){
                //One hair at a time
                sendMessage(session, message);
            }
        }
    }

    /**
     * Send a message to the specified client
     * This method can be upgraded to instant messaging tools, such as client A, client B, and server WS
     * First of all, the client must have an identity id to bind to the session of WS
     * Then, if A wants to send A message to B, first obtain B's identity id, and then send the message and B's identity id to WS
     * WS After receiving the message of A, take the id of B to query the session information of B and WS, find it, and send the message of A to B
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public void sendMessage(String sessionId,String message) throws IOException {
        Session session = null;
        //Traverse to find session information
        for (Session s : sessions) {
            if(s.getId().equals(sessionId)){
                session = s;
                break;
            }
        }
        if(session!=null){
            //Found it. Send a message
            this.sendMessage(session, message);
        } else{
            //Print log
            log.warn("The specified session was not found:",sessionId);
        }
    }
}

Here, the WebSocket server is configured.

JS client

JS client is actually a piece of JS code running on the browser. As long as the browser supports WebSocket protocol, it can communicate with the server

Create html page

The code is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
JSClient page
</body>
</html>

Write JS client code

Just write it in the page. The code is as follows

<script type="text/javascript">
    var socket;
    if (typeof (WebSocket) == "undefined") {
        console.log("Sorry: your browser does not support WebSocket");
    } else {
        console.log("Congratulations: your browser supports WebSocket");

        //Implementing WebSocket objects
        //Specify the server address and port to connect to
        socket = new WebSocket("ws://localhost:8080/ws/server");
        //Connection open event
        socket.onopen = function() {
            console.log("Socket Already opened");
            socket.send("Message sending test(From Client)");
        };
        //Receive message event
        socket.onmessage = function(msg) {
            console.log(msg.data);
        };
        //Connection close event
        socket.onclose = function() {
            console.log("Socket Closed");
        };
        //An error event occurred
        socket.onerror = function() {
            alert("Socket An error has occurred");
        }
        //When the window is closed, close the connection
        window.unload=function() {
            socket.close();
        };
    }
</script>

Verify WebSocket communication

Open two pages, open the console, see the effect, other verification will not be introduced, as long as you can connect, anything can be solved! ~
First page:

Second page:

Tags: Session socket Spring Java

Posted on Mon, 02 Dec 2019 12:37:21 -0800 by glima