Wechat search a search: technology cat, get the first time update, share software, technology, programming.

Maven rely on

		<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>
Copy the code

The project structure

Websocket configuration class

package com.websocket.websocket.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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 // Enable WebSocket functions
public class WebSocketServerConfig implements WebSocketConfigurer {
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    @Autowired
    private MyHandshakeInterceptor myHandshakeInterceptor;

    /** * MyWebSocketHandler is used to handle sessions ** when the client communicates with the server connection via /connect@param webSocketHandlerRegistry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        // Add a handler and define the handler's processing path (note: 403 +. SetAllowedOrigins ("*"))
        webSocketHandlerRegistry.addHandler(myWebSocketHandler, "/ws").addInterceptors(myHandshakeInterceptor).setAllowedOrigins("*");
        WithSockJS (), SockJS is used by Spring to handle browser compatibility with Websocket. * SockJS provides webSocket requests in three different ways, depending on whether the browser supports websocket, namely webSocket, HTTP Streaming, and HTTP Long Polling */
        webSocketHandlerRegistry.addHandler(myWebSocketHandler, "/ws/sockjs").addInterceptors(myHandshakeInterceptor).withSockJS(); }}Copy the code
package com.websocket.websocket.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

@Component
public class MyWebSocketHandler implements WebSocketHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /** * This method is triggered when the client connection is successful@param webSocketSession
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        log.info("Establish a connection with the client");
    }

    /** * After establishing a connection with the client, process the request sent by the client **@param webSocketSession
     * @param webSocketMessage
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage
        webSocketMessage) throws Exception {
        Object content = webSocketMessage.getPayload();
        log.info(content.toString());
        // Send messages to the client
        webSocketSession.sendMessage(new TextMessage(fakeAi(content.toString())));
    }

    private static String fakeAi(String input) {
        if (input == null || "".equals(input)) {
            return "What did you say? Didn't catch ︎";
        }
        return input.replace('you'.'我')
                .replace("吗"."")
                .replace('? '.'! ')
                .replace('? '.'! ');
    }

    /** * This method is triggered when the connection to the client fails@param webSocketSession
     * @param throwable
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        webSocketSession.close(CloseStatus.SERVER_ERROR);
        log.error("Abnormal connection", throwable);
    }

    /** * This method is triggered when the client is disconnected@param webSocketSession
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        log.info("Disconnect");
    }

    /** * Whether some messages are supported: If set to true, a large or unknown size message will be split and received multiple times (by calling handleMessage(WebSocketSession, WebSocketMessage).) * If split into multiple messages, You can through an API: org. Springframework. Web. Socket. WebSocketMessage. IsLast () is the end of a message. * Default is usually false and messages are not split * *@return* /
    @Override
    public boolean supportsPartialMessages(a) {
        return false; }}Copy the code
package com.websocket.websocket.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class MyHandshakeInterceptor implements HandshakeInterceptor {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /** * if false is returned before the handshake, the link is not established@param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        // Establish a persistent connection with a handshake
        log.info("Good handshake."); }}Copy the code

The front end

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"> <title>WebSocket client </title> <script SRC ="https://cdn.bootcss.com/sockjs-client/0.3.4/sockjs.min.js"></script>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<style>
    .jumbotron {
        width: 100%;
    }

    #text {
        height: 3rem;
        font-size: 1rem;
        line-height: 3rem;
        margin: 1rem;
    }

    .btn {
        margin-right: 5px;
    }

    #connect {
        margin-left: 1rem;
    }

    #log {
        margin: 1rem 0 0 1rem;
    }

</style>
<div class="container">
    <div class="row">
        <div class="jumbotron">
            <input type="text" placeholder="Please enter what you want to transmit." id="text" class="col-lg-12"/>
            <input type="button" value="Connection" class="btn btn-info" id="connect" onclick="connect()"/>
            <input type="button" value="Send" class="btn btn-success" id="sent" disabled="disabled" onclick="sent()"/>
            <input type="button" value="Disconnect" class="btn btn-danger" id="disconnect" disabled="disabled"
                   onclick="disconnect()"/>

            <div id="log"> < p > chat record: < / p > < / div > < / div > < / div > < / div > < script type ="text/javascript">
    let text = document.querySelector('#text');
    let connectBtn = document.querySelector("#connect");
    let sentBtn = document.querySelector("#sent");
    let disconnectBtn = document.querySelector("#disconnect");
    let logDiv = document.querySelector("#log");

    let ws = null;

    function connect(a) {
        let targetUri = "/ws/sockjs";
        ws = new SockJS(targetUri);
        ws.onopen = function () {
            setConnected(true);
            log('Connection to server successful! ');
        };
        ws.onmessage = function (event) {
            log('The server says:' + event.data);
        };
        ws.onclose = function () {
            setConnected(false);
            log('Disconnect from the server! ')}}function sent(a) {
        if(ws ! =null) {
            ws.send(text.value);
            log('The client says:' + text.value);
        } else {
            log('Please establish a connection first! ')}}function disconnect(a) {
        if(ws ! =null) {
            ws.close();
            ws = null;
        }
        setConnected(false);
    }

    function log(value) {
        let content = document.createElement('p');
        content.innerHTML = value;
        logDiv.appendChild(content);
        text.value = ' ';
    }

    function setConnected(connected) { connectBtn.disabled = connected; disconnectBtn.disabled = ! connected; sentBtn.disabled = ! connected; } </script> </body> </html>Copy the code

The effect