How to Use websocket to Realize Front-end and Back-end Communication

Keywords: Java Session Spring xml

websocket communication is a very interesting and useful way of communication. The ways of using it are as follows:


The first step is to introduce dependencies in the pom.xml file because spring boot integrates websocket well.


The second step is to use websocket in the front-end interface, which is written in HTML files.

    var websocket = null;
    if('WebSocket' in window) {
        websocket = new WebSocket('ws://');
    }else {
        alert('This browser does not support websocket!');

    websocket.onopen = function (event) {
        console.log('Establish connection');

    websocket.onclose = function (event) {
        console.log('Connection closure');

    websocket.onmessage = function (event) {
        console.log('Receive message:' +
        //The operation to be performed

    websocket.onerror = function () {
        alert('websocket Communication error!');

    window.onbeforeunload = function () {


The third step is that we usually interact in the controller layer, but the interaction of websocket is in the service layer.

Among them:

@ ServerEndpoint("/webSocket") is the address that defines the interaction
@ Slf4j is a log, interested in understanding, please read this article
@ The three methods of OnOpen, @OnClose, @OnMessage interact with the three homonymous methods of the front end. The methods are called in the places where they need to be used as follows.
It's almost finished here.
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();
    public void onOpen(Session session){
        webSocketSet.add(this);"[websocket There are new connections, total:{}",webSocketSet.size());
    public void onClose(){
        webSocketSet.remove(this);"[websocket Message) Connection disconnected, total:{}",webSocketSet.size());
    public void onMessage(String message){"[websocket Message) Received the message from the client:{}",message);
    public void sendMessage(String message){
        for(WebSocket webSocket:webSocketSet){
  "[websocket Broadcast news:{}",message);
            try {
            } catch (IOException e) {

How to use it:

private WebSocket webSocket;
webSocket.sendMessage("Transferred parameters");

Posted by ILYAS415 on Sat, 05 Oct 2019 22:44:57 -0700