Front-end and back-end interaction of websocket

WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a handshake, and a persistent connection can be created directly between the two, and two-way data transmission can be performed.

Simulate actual combat scenarios: the backend pushes alarm information to the frontend through websocket, and the frontend sends some information to the backend.

Backend websocket related code:

 Among them, the websocket package is the configuration code related to websockt, and the job is the timing task, which is responsible for pushing the alarm message



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/websocket").setAllowedOrigins("*");
    }

    @Bean
    public WebSocketHandler myHandler() {
        return new MyWebSocketHandler();
    }
}

The WebSocketConfig class listens to requests from all domains under the /websocket path, please set it in actual development
AllowedOrigins is the domain name of the internal front-end page


import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashSet;
import java.util.Set;

public class MyWebSocketHandler extends TextWebSocketHandler {

    public static Set<WebSocketSession> sessions = new HashSet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        session.sendMessage(new TextMessage("客户端连接成功"));
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message)
            throws Exception {
        System.out.println("收到消息: " + message.getPayload());
        session.sendMessage(new TextMessage("后端已经收到: " + message.getPayload()));

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        sessions.remove(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }
}
The MyWebSocketHandler class inherits from AbstractWebSocketHandler
It mainly rewrites the operations after the connection is established, and the operations after receiving the front-end message; after the transmission error or the connection is closed, the session pool will remove the session.


import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

@Service
public class WebscoketService {


    public void sendAllMessages(String text) throws IOException {
        for (WebSocketSession session : MyWebSocketHandler.sessions) {
            session.sendMessage(new TextMessage(text));
        }
    }
}

The service layer pushes messages to all connections in the session pool.

import com.hn.managmentsystem.websocket.WebscoketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AlarmPushJob {

    @Autowired
    private WebscoketService webscoketService;

    @Scheduled(cron = "*/5 * * * * ?")
    private void pushAlarm() throws IOException {
        System.out.println("开始执行");
        webscoketService.sendAllMessages("告警推送");
    }
}

Push scheduled jobs

Front-end page code:

<html>
<script type="text/javascript">
    if ("WebSocket" in window) {
        var ws = new WebSocket("ws://localhost:18080/websocket");
        ws.onopen = function () {

        };

        ws.onmessage = function (evt) {
            document.getElementById('messageDiv').innerHTML += evt.data + "</br>";
        };

        ws.onclose = function () {
            console.log("close connect");
        };
    } else {
        alert("您的浏览器不支持 WebSocket!");
    }

    function send() {
        ws.send(document.getElementById("message").value);
    }
</script>

</head>
<body>
<a href="#" onclick="send();">发送消息</a>: <input id="message"/>
<div id="messageDiv"></div>
</body>
</html>

actual effect:

Guess you like

Origin blog.csdn.net/babing18258840900/article/details/123246941