Home > Web Front-end > Front-end Q&A > Chat built by nodejs sse

Chat built by nodejs sse

WBOY
Release: 2023-05-23 19:07:36
Original
750 people have browsed it

Chat room built by Node.js SSE

With the popularity and development of the Internet, chat rooms have become an important platform for people's daily online communication. As a server-side JavaScript language based on event-driven and non-blocking I/O models, Node.js can greatly improve the performance and responsiveness of applications, and therefore has become one of the preferred technologies for many web applications.

This article will introduce how to use Node.js and SSE (Server-Sent Events) technology to build a simple chat room so that users can receive chat messages in real time.

  1. Node.js and SSE

SSE is a technology defined in HTML5 that allows the server to send a stream of events to the client, and the client can use EventSource API to receive these event streams. In this event stream, the server can send messages to the client in real time, and the client can also interact by sending data to the server.

Node.js can easily create a web server, and it has a built-in HTTP module that can be used to handle HTTP requests and responses. Through this module, we can easily implement SSE technology.

  1. Build a chat room

2.1 Create a server

First, we need to create a Node.js project. In the root directory of the project, we create a server.js file and introduce the http module.

const http = require('http');
Copy after login

Then, we need to create an HTTP server and listen on port 8080.

const server = http.createServer((req, res) => {
  // 代码稍后补充
});
server.listen(8080);
Copy after login

2.2 SSE technology implementation

We need to create a route on the server for sending event streams. In this route, we will use the EventSource API to send messages to the client.

const SSE_SEND_CONTENT_TYPE = 'text/event-stream; charset=utf-8';
const SSE_SEND_DATA_PREFIX = 'data: ';
const SSE_SEND_EVENT_PREFIX = 'event: ';
const SSE_SEND_ID_PREFIX = 'id: ';
const SSE_SEND_RETRY_PREFIX = 'retry: ';

const headers = {
    'Content-Type': SSE_SEND_CONTENT_TYPE,
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
};

server.on('request', (req, res) => {
    if (req.method === 'GET' && req.url === '/chat') {
        res.writeHead(200, headers);

        const clientId = Date.now();
        const sseStream = new ServerSentEventsStream(clientId, res);
        clients.set(clientId, sseStream);

        req.on('close', () => {
            clients.delete(clientId);
            sseStream.close();
        });
    } else {
        res.writeHead(404);
        res.end();
    }
});

class ServerSentEventsStream {
    constructor(clientId, response) {
        this.clientId = clientId;
        this.response = response;
        this.closed = false;
    }

    sendEvent(event, data) {
        if (!this.closed) {
            const message = `${SSE_SEND_EVENT_PREFIX} ${event}
${SSE_SEND_DATA_PREFIX}${JSON.stringify(data)}

`;
            this.response.write(message);
        }
    }

    close() {
        if (!this.closed) {
            this.closed = true;
            this.response.end();
        }
    }
}
Copy after login

2.3 Implementing the chat room function

After completing the above steps, we can now implement basic SSE technology on the server. Next, we need to implement the chat function on the client.

We need to create an HTML page on the client to display chat information. In this page, we will use JavaScript to send chat messages and receive messages returned by the server. And, we also need to use the EventSource API to listen for messages sent by the server.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chatroom</title>
</head>
<body>
  <form id="chat-form">
    <input type="text" id="msg-input" placeholder="Enter message">
    <button type="submit" id="send-button">Send</button>
  </form>
  <ul id="chat-list"></ul>
  <script>
    const chatList = document.getElementById('chat-list');
    const chatForm = document.getElementById('chat-form');
    const msgInput = document.getElementById('msg-input');
    const sendButton = document.getElementById('send-button');

    const eventSource = new EventSource('/chat');
    eventSource.onmessage = function(event) {
      const chatMsg = JSON.parse(event.data);
      const chatItem = document.createElement('li');
      chatItem.innerText = `${chatMsg.sender}: ${chatMsg.msg}`;
      chatList.appendChild(chatItem);
    }

    chatForm.addEventListener('submit', function(event) {
      event.preventDefault();
      const formData = new FormData(chatForm);
      fetch('/chat', { method: 'POST', body: formData });
      msgInput.value = '';
    });
  </script>
</body>
</html>
Copy after login

In the above code, we create a form that allows users to enter chat information. When the user submits this form, we will use the fetch API to send the user's message to the server.

At the same time, we also listened to all messages returned from the server. When the server sends a chat message, we add the message to the already created chat list.

  1. Summary

This article introduces the process of using Node.js and SSE technology to create a simple chat room. Through the example of this chat room, we can also learn how to use SSE technology, as well as the collaboration methods and advantages of JavaScript and Node.js, which provides a good reference for our subsequent web development work.

The above is the detailed content of Chat built by nodejs sse. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template