The difference between short polling, long polling, SSE and WebSocket

Realization of instant messaging: the difference between short polling, long polling, SSE and WebSocket

Learning Content:

Short polling: Short polling is a method of communication between a client and a server, where the client periodically sends a request to the server to check for new messages. If there are no new messages, the server returns an empty response. The disadvantage of this approach is the high frequency of requests sent by clients, which can lead to network congestion and high server load.

Long polling: Long polling is an improved polling method in which the client sends a request and keeps the connection open until a new message is available from the server or the connection times out. This approach reduces unnecessary requests, but still requires sending a large number of HTTP requests.

SSE: SSE (Server-Sent Events) is a one-way communication protocol in which the server can push messages to the client. Unlike polling, the client only needs to send one request, and the server can send new messages at any time. This approach reduces network traffic and server load.

WebSocket: WebSocket is a two-way communication protocol that allows a server and client to communicate in real time with a connection open. WebSocket can reduce network traffic and server load because it does not require the client to send a large number of HTTP requests to get new messages.

Example:

Short polling: The chat feature in a social media application uses short polling to check for new messages.

Long polling: In online games, players use long polling to obtain real-time positions and actions of other players.

SSE: News sites can use SSE to push news headlines and summaries to users without requiring them to manually refresh the page.

WebSocket: Online meeting software uses WebSocket for real-time audio and video communication, as well as document and screen sharing during meetings.

Short polling and long polling are HTTP-based polling techniques, SSE is a one-way communication protocol, and WebSocket is a two-way communication protocol. Compared with other technologies, WebSocket has better performance and lower latency, so it has become the technology of choice for instant messaging.

How to use WebSocket:

1. Create a WebSocket object: You can use JavaScript's WebSocket API to create a WebSocket object on the client side. For example, the following code can be used to create a WebSocket object and connect to a server:

const socket = new WebSocket('ws://localhost:8080/my-websocket');

2. Handle WebSocket events: WebSocket objects have multiple events that can be used to handle connection status, receive and send data, and more. For example, the following code can be used to listen to the open event of a WebSocket object:
some are shown below 内联代码片.

socket.addEventListener('open', (event) => {
    
    
  console.log('WebSocket 连接已打开');
});

3. Sending and receiving data: You can use the send() method of the WebSocket object to send data to the server, or you can use the onmessage event to receive data from the server. For example, the following code can be used to send a message and handle the response from the server:

socket.send('Hello, server!');

socket.addEventListener('message', (event) => {
    
    
  console.log('服务器返回数据:', event.data);
});

4. Close the WebSocket connection: When the WebSocket connection is no longer needed, the close() method of the WebSocket object can be used to close the connection. For example, a WebSocket connection can be closed using the following code:

socket.close();

It should be noted that WebSocket connections need to be supported on the server side as well. The server needs to implement the WebSocket protocol and listen to the client's connection request. In addition, the WebSocket connection needs to be used under a secure HTTPS connection, or use the ws:// protocol in the local development environment.

How to write WebSocket backend spring boot

1. Add dependencies

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

2. Create a WebSocket configuration class

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    
    

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    
    
        registry.addHandler(myWebSocketHandler(), "/my-websocket")
                .setAllowedOrigins("*");
    }

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

In this example, we create a WebSocket handler MyWebSocketHandler and register it under the "/my-websocket" path. setAllowedOrigins("*") allows clients from any origin to connect to the WebSocket.

3. Create a WebSocket handler

public class MyWebSocketHandler implements WebSocketHandler {
    
    

    private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    
    
        sessions.add(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
    
    
        for (WebSocketSession s : sessions) {
    
    
            if (s.isOpen() && !s.getId().equals(session.getId())) {
    
    
                s.sendMessage(message);
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    
    
        sessions.remove(session);
    }
}

This handler maintains a list of WebSocketSessions for all clients connected to the WebSocket. Every time a new client connects to the WebSocket, the afterConnectionEstablished() method will be called, where we add the new client's WebSocketSession to the list. When a client sends a message, the handleMessage() method will be called, where we forward the message to all other clients. When a client disconnects, the afterConnectionClosed() method will be called, where we remove the disconnected client from the list.
4. Test WebSocket

const socket = new WebSocket("ws://localhost:8080/my-websocket");
socket.onmessage = (event) => {
    
    
    console.log("收到消息:", event.data);
};
socket.send("Hello, world!");

When a client sends a message, the handleMessage() method of MyWebSocketHandler will be called to forward the message to all other clients.

Guess you like

Origin blog.csdn.net/u013194063/article/details/130288516