WebSocket notes + SpringBoot integration

Posted by vfwood on Tue, 25 Jan 2022 07:17:26 +0100

WebSocket notes

Websocket: HTML5 WebSocket is designed to replace polling and long connection, so that the client browser has the instant messaging capability of desktop system under C/S framework, and realizes full duplex communication between browser and server. It is based on TCP. Although websocket transmits data through TCP like HTTP, websocket can actively send or receive data to each other, Just like Socket; Moreover, websocket needs a TCP like client and server to connect through handshake. Only after the connection is successful can they communicate with each other.

Advantages: two-way communication, event driven, asynchronous, client using ws or wss protocol can really realize push function in a sense.

Disadvantages: a few browsers do not support it.

Examples: social chat (wechat, QQ), bullet screen, multi player game playing, collaborative editing, real-time stock fund quotation, sports live update, video conference / chat, location-based application, online education, smart home and other high real-time scenes.

Constructor

WebSocket(url[, protocols\]) Returns a WebSocket object.

constant

ConstantValue
WebSocket.CONNECTING0
WebSocket.OPEN1
WebSocket.CLOSING2
WebSocket.CLOSED3

attribute

method

event

Use addEventListener() or assign an event listener to the on*eventname * attribute of this interface to listen to the following events.

  • close

    Triggered when a WebSocket connection is closed. You can also pass onclose Property.

  • error

    Triggered when a WebSocket connection is closed due to an error, such as when data cannot be sent. You can also pass onerror Property

  • message

    Triggered when data is received through WebSocket. You can also onmessage Property.

  • open

    Triggered when a WebSocket connection succeeds. You can also onopen Property.

Example

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

SpringBoot integrates WebSocket

Pom.xml file

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

Configuration class

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

WebSocket server class

@ServerEndpoint(value = "/websocketTest/{userId}")
@Component
@Slf4j
public class TestWebSocket {
    private static Map<String,Session> userMap = new HashMap<>();

    @OnOpen//Triggered when a 'WebSocket' connection succeeds
    public void onOpen(Session session, @PathParam("userId") String userId){
        userMap.put(session.getId(), session);
        log.debug("Create a new connection:{}", userId);
    }

    @OnClose//Triggered when a 'WebSocket' connection is closed
    public void onClose(Session session){
        //Remove chat messages from when closed
        userMap.remove(session.getId());
        log.debug("connect:{}to break off",session.getId());
    }

    @OnMessage//Triggered when a 'WebSocket' connection is closed
    public void onMessage(String message,Session session) throws IOException {
        log.debug("Received user{}News of{}",session.getId(),message);
        //Send message as broadcast
        Iterator<Map.Entry<String, Session>> radioBroadcast = userMap.entrySet().iterator();
        while(radioBroadcast.hasNext()){
            Map.Entry<String, Session> next = radioBroadcast.next();
            next.getValue().getBasicRemote().sendText(session.getId()+"The message sent is:"+message);
        }
    }

    @OnError//Triggered when a 'WebSocket' connection is closed due to an error
    public void onError(Session session,Throwable error){
        log.debug("user id by:{}Connection send error",session.getId());
        error.printStackTrace();
    }
}

Front page

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
websocket Demo---- user000 <br />
<input id="text" type="text" />
<button onclick="send()"> Send </button>
<button onclick="closeWebSocket()"> Close </button>
<div id="message">   </div>
<script type="text/javascript">
    //Judge whether the current browser supports WebSocket
    if('WebSocket' in window){
        console.log("link success");

        websocket = new WebSocket("ws://localhost:8080/websocketTest/user001");
    }else{
        alert('Not support websocket')
    }

    //Callback method with connection error
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //Callback method for successful connection establishment
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    };

    //Callback method for receiving message
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    };

    //Callback method for connection closure
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    };

    //Display messages on Web pages
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //send message
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
    
     //Close connection
    function closeWebSocket(){
        websocket.close();
    }
    
    //Listen for window closing events. When the window is closed, take the initiative to close the websocket connection to prevent closing the window before the connection is disconnected, and the server side will throw exceptions.
    window.onbeforeunload = function(){
        websocket.close();
    };
</script>

</body>
</html>

Topics: socket Spring Boot Network Protocol websocket