Implementation of message push based on Tomcat 8 in websocket

Keywords: Mobile Session Tomcat Spring Javascript

To implement back-end push to front-end messages, the old practice is front-end polling, which is not done now.
Now using websocket to implement, there are many APIs to implement websocket, which are based on Tomcat 8.
1. Build a new spring boot project first.
2. Create a new config class

/**
 * @author smy
 */
@Configuration
public class WebConfig {
    /**
     * Support for websocket
     * If built-in tomcat is not used, no configuration is required
     * @return
     */
    @Bean
    public ServerEndpointExporter createServerEndExporter(){
        return new ServerEndpointExporter();
    }
}

3. Build a message configuration management class where myWebSocket is the front-end call interface.

/**
 * websocket Server side
 * @author smy
 */
@Component
@ServerEndpoint(value = "/myWebSocket")
public class MyWebSocket {

    //The MyWebSocket object used to store the corresponding MyWebSocket object for each client
    private static CopyOnWriteArraySet<MyWebSocket> user = new CopyOnWriteArraySet<MyWebSocket>();

    //Connecting session with a client needs to be used to send data to the client
    private Session session;

    @OnMessage
    public void onMessage(String message,Session session) throws IOException {

        //Mass message
        for (MyWebSocket myWebSocket : user) {
            myWebSocket.session.getBasicRemote().sendText(session.getId()+"Said:"+message);
            //myWebSocket.session.getBasicRemote().sendText("<img src=''/>");
        }
    }

    @OnOpen
    public void onOpen(Session session){
        System.out.println(session.getId()+" open...");
        this.session = session;
        user.add(this);
    }
    @OnClose
    public void onClose(){
        System.out.println(this.session.getId()+" close...");
        user.remove(this);
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println(this.session.getId()+" error...");
        error.printStackTrace();
    }

}

4. Front-end page

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        #message{
            height: 520px;
            border-bottom: 1px solid gray;
            padding: 20px 30px;
        }
        #container{
            margin: 0 auto;
            width: 720px;
            border: 1px solid gray
        }
        input{
            width: 300px;
            height: 36px;
            border: 1px solid gray;
            background:none;
            outline:none;
        }
        input:focus{
            border-color: yellow;
        }
        button{
            height: 36px;
        }
    </style>
</head>
<body>
<div id="container">
    <div id="message">

    </div>
    <div>
        <input id="text" type="text" placeholder="Input content..."/>
        <button onclick="send()">send message</button>
    </div>
</div>
<script th:inline="javascript" type="text/javascript">
    var websocket = null;

    //Determine whether the current browser supports WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8088/myWebSocket");
    }
    else {
        alert('Current browsers do not support websocket');
    }

    //send message
    function send() {
        debugger;
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
    //Callback Method for Receiving Messages
    websocket.onmessage = function (event) {
        debugger;
        var data = event.data;
        document.getElementById('message').innerHTML += data+'<br/>';
    }

    //Callback method for successful connection establishment
    websocket.onopen = function () {
        console.log("onopen...");
    }
    //Callback method for connection closure
    websocket.onclose = function () {
        console.log("onclose...");
    }
    //Callback method for connection error
    websocket.onerror = function () {
        console.log("onerror...");
    };
    //Listen for window closure events. When the window closes, take the initiative to close the websocket connection to prevent the window from closing before the connection is disconnected. The server side will throw an exception.
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    //Close the WebSocket connection
    function closeWebSocket() {
        websocket.close();
    }

</script>
</body>
</html>

So far, the function has been completed.
Oak, please visit http://127.0.0.1:8088/home.html Don't ask me why!
The code has been packaged, uploaded, downloaded and run directly.


The implementation based on spring and stomp will be updated in the future.

My code cloud address: https://gitee.com/renting/websocket_test

Posted by swr on Sat, 05 Oct 2019 05:38:50 -0700