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.

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

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

<script>
    var websocket = null;
    if('WebSocket' in window) {
        websocket = new WebSocket('ws://yesell.natapp1.cc/sell/webSocket');
    }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:' + event.data)
        //The operation to be performed
    }

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

    window.onbeforeunload = function () {
        websocket.close();
    }

</script>

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 https://www.cnblogs.com/yemengshen/p/11478293.html
@ 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.
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();
    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);
        log.info("[websocket There are new connections, total:{}",webSocketSet.size());
    }
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        log.info("[websocket Message) Connection disconnected, total:{}",webSocketSet.size());
    }
    @OnMessage
    public void onMessage(String message){
        log.info("[websocket Message) Received the message from the client:{}",message);
    }
    public void sendMessage(String message){
        for(WebSocket webSocket:webSocketSet){
            log.info("[websocket Broadcast news:{}",message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

How to use it:

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

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