乐闻世界logo
搜索文章和话题

How Server Sent Event send response to a specific client

1个答案

1

Server-Sent Events (SSE) is a technology that enables servers to actively push information to client browsers. It serves as a lightweight alternative to WebSocket, built upon HTTP, and is particularly suited for one-way data streaming scenarios such as real-time notifications and live data updates.

How to Send Responses to Specific Clients:

  1. Client Identification: To send messages to a specific client, you must first establish a way to uniquely identify and distinguish each client. This is commonly achieved using a Session ID, Token, or a custom client ID. When a client initially connects to the server, include this identifier in the request.

    javascript
    // Client-side code var eventSource = new EventSource("/events?clientId=12345");
  2. Server-side Processing: Upon receiving a connection request, the server parses the identifier from the request and associates it with the corresponding connection. This allows the server to efficiently track which message should be delivered to which client.

    python
    # Server-side pseudo-code clients = {} def on_new_connection(request): client_id = request.query['clientId'] clients[client_id] = request.connection
  3. Sending Messages: When sending a message to a specific client, the server retrieves the previously stored connection object and transmits the message through it. This ensures messages are delivered exclusively to the intended client, even when multiple clients are connected.

    python
    # Server-side pseudo-code def send_message_to_client(client_id, message): if client_id in clients: connection = clients[client_id] connection.send(message)
  4. Application Example: Consider a real-time stock price update system where each client may subscribe to only a subset of stocks. The server can send relevant updates based on the stock codes each client has subscribed to.

    python
    # User subscriptions to specific stocks subscriptions = { 'client1': ['AAPL', 'GOOGL'], 'client2': ['MSFT'] } # Sending updates based on subscriptions def update_price(stock_code, price): for client_id, stocks in subscriptions.items(): if stock_code in stocks: send_message_to_client(client_id, f"{stock_code} price is {price}")

Summary: By leveraging client identification to establish persistent connections and linking these identifiers to specific data or channels, Server-Sent Events effectively target messages to specific clients. This approach is highly valuable for scenarios requiring efficient, real-time, and one-way data transmission.

2024年8月15日 20:25 回复

你的答案