The difference between webSocket and EventSource

WebSocket and EventSource are two different technologies used in web applications to achieve real-time communication. WebSocket is a two-way communication protocol that allows a server to establish a persistent connection with a client and send messages over that connection. And EventSource is a server push technology that only allows the server to send messages to the client, but does not allow the client to send messages to the server. In the following description, I will detail the differences between WebSocket and EventSource and provide some code examples.

WebSocket

WebSocket is a two-way communication protocol built on top of HTTP that allows a server to establish a persistent connection with a client and send messages over that connection. This two-way communication can make web applications more real-time and dynamic. The most common scenarios for using WebSockets are applications that require fast real-time response, such as online chat rooms, multiplayer games, and stock markets. The WebSocket protocol is based on the TCP protocol, so it has the characteristics of efficient, reliable data transmission and low latency. Here is a simple WebSocket example:

// 客户端代码
const socket = new WebSocket('ws://localhost:3000');
socket.addEventListener('open', (event) => {
    
    
  console.log('WebSocket连接已打开');
  socket.send('Hello, WebSocket!');
});
socket.addEventListener('message', (event) => {
    
    
  console.log(`接收到消息: ${
      
      event.data}`);
});
socket.addEventListener('close', (event) => {
    
    
  console.log('WebSocket连接已关闭');
});

// 服务器代码
const WebSocket = require('ws');
const wss = new WebSocket.Server({
    
     port: 3000 });
wss.on('connection', (ws) => {
    
    
  console.log('WebSocket连接已建立');
  ws.send('Hello, WebSocket!');
  ws.on('message', (data) => {
    
    
    console.log(`接收到消息: ${
      
      data}`);
    ws.send(`你发送了: ${
      
      data}`);
  });
  ws.on('close', () => {
    
    
    console.log('WebSocket连接已关闭');
  });
});

In this example, the client creates a WebSocket connection using the WebSocket object, sends a message and listens for message events when the connection is opened. The server creates a WebSocket server using the WebSocket.Server object, sends a message when there is a new connection and listens for message events. When a new message arrives, the server sends the message back to the client. When the connection is closed, both the server and the client execute corresponding processing logic.

EventSource

EventSource is a server push technology that allows the server to send messages to the client without the client being able to send messages to the server. This technique can be used to implement real-time updates on the server side, such as real-time stock quotes, weather forecasts, social media notifications, etc. The EventSource protocol is based on the HTTP protocol, so it can be deployed through standard HTTP servers. Here is a simple EventSource example:

// 客户端代码
const eventSource = new EventSource('/events');
eventSource.addEventListener('open', (event) => {
    
    
  console.log('EventSource连接已打开');
});
eventSource.addEventListener('message', (event) => {
    
    
  console.log(`接收到消息: ${
      
      event.data}`);
});
eventSource.addEventListener('error', (event) => {
    
    
  console.log('EventSource连接已关闭');
});

// 服务器代码
const http = require('http');
const server = http.createServer((req, res) => {
    
    
  if (req.url === '/events') {
    
    
    res.writeHead(200, {
    
    
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive'
    });
    setInterval(() => {
    
    
      res.write(`data: ${
      
      new Date().toLocaleTimeString()}\n\n`);
    }, 1000);
  } else {
    
    
    res.writeHead(404);
    res.end();
  }
});
server.listen(3000, () => {
    
    
  console.log('服务器已启动');
});

In this example, the client creates an EventSource connection using the EventSource object and listens for open, message, and error events when the connection is opened. The server creates an HTTP server that, upon receiving a request for the /events path, returns a response with a MIME type of text/event-stream that contains an infinite loop that periodically sends a message. When the client receives these messages, it displays them in the console.

the difference

The difference between WebSocket and EventSource lies in their two-way communication capabilities, connection management, protocol specification, and data format. WebSocket is a two-way communication protocol that allows real-time two-way communication between a client and a server. WebSocket connections are persistent and can remain connected until one of the parties closes the connection. The WebSocket protocol specification includes data formats and control frames that allow applications to send control information during data transfers. On the other hand, EventSource is a server push technology that only allows the server to send messages to the client. EventSource connection is one-way, only from server to client, not from client to server. The EventSource protocol specification only includes the data format, not the control frame.

Both WebSocket and EventSource have their own advantages and disadvantages and applicable scenarios. WebSocket is suitable for applications that require real-time, two-way communication, such as online chat rooms, multiplayer games, and stock markets. EventSource is suitable for applications that need to implement real-time updates on the server side, such as real-time stock quotes, weather forecasts, social media notifications, etc.

In summary, both WebSocket and EventSource are effective technologies for real-time communication. Which technology to choose depends on the specific needs and use cases of the application. The following is an example of a simple chat room implemented using WebSocket to illustrate the two-way communication capability of WebSocket:

// 客户端代码
const socket = new WebSocket('ws://localhost:3000');
socket.addEventListener('open', (event) => {
    
    
  console.log('WebSocket连接已打开');
  socket.send('Hello, WebSocket!');
});
socket.addEventListener('message', (event) => {
    
    
  console.log(`接收到消息: ${
      
      event.data}`);
});
socket.addEventListener('close', (event) => {
    
    
  console.log('WebSocket连接已关闭');
});

// 服务器代码
const WebSocket = require('ws');
const wss = new WebSocket.Server({
    
     port: 3000 });
wss.on('connection', (ws) => {
    
    
  console.log('WebSocket连接已建立');
  ws.send('欢迎加入聊天室!');
  ws.on('message', (data) => {
    
    
    console.log(`接收到消息: ${
      
      data}`);
    wss.clients.forEach((client) => {
    
    
      if (client.readyState === WebSocket.OPEN) {
    
    
        client.send(data);
      }
    });
  });
  ws.on('close', () => {
    
    
    console.log('WebSocket连接已关闭');
  });
});

In this example, both client and server can send and receive messages over a WebSocket connection for two-way communication. Clients can send messages and listen to message events, and servers can receive messages and broadcast them to all clients.

Supongo que te gusta

Origin blog.csdn.net/ZTAHNG/article/details/131590363
Recomendado
Clasificación