Home > Web Front-end > JS Tutorial > body text

Build a real-time chat room based on JavaScript

王林
Release: 2023-08-10 23:18:16
Original
1293 people have browsed it

Build a real-time chat room based on JavaScript

Building a real-time chat room based on JavaScript

With the rapid development of the Internet, people are paying more and more attention to instant messaging and real-time interactive experience. As a common instant messaging tool, real-time chat rooms are very important to both individuals and businesses. This article will introduce how to build a simple real-time chat room using JavaScript and provide corresponding code examples.

We first need a front-end page as the UI interface of the chat room. Here is a simple HTML structure example:

<!DOCTYPE html>
<html>
<head>
    <title>实时聊天室</title>
    <style>
        #messages {
            height: 400px;
            overflow: scroll;
            border: 1px solid grey;
        }
    </style>
</head>
<body>
    <div id="messages"></div>
    <input type="text" id="input" placeholder="输入消息">
    <button onclick="sendMessage()">发送</button>
</body>
</html>
Copy after login

In the above code, we have created a <div> element to display the message and set a fixed height and scrollbar style . Next, we added a text box and a button where the user can type a message and a button to send it.

Next, we need to write the corresponding JavaScript code to handle the logic of the real-time chat room. The following is a simple implementation example:

// 创建一个WebSocket连接
const socket = new WebSocket('ws://localhost:3000');

// 当连接建立时执行
socket.onopen = function(event) {
    console.log('已连接到服务器');
};

// 当收到服务器消息时执行
socket.onmessage = function(event) {
    const messages = document.getElementById('messages');
    const message = document.createElement('div');
    message.innerText = event.data;
    messages.appendChild(message);
    // 滚动到最底部
    messages.scrollTop = messages.scrollHeight;
};

// 发送消息
function sendMessage() {
    const input = document.getElementById('input');
    const message = input.value;
    socket.send(message);
    input.value = '';
}
Copy after login

In the above code, we use the WebSocket API in JavaScript to establish a real-time connection with the server. When the connection is successfully established, we will receive an onopen event. When a message is received from the server, the onmessage event will be triggered. We will add the received message to the message display area and automatically scroll to the bottom by setting the scroll bar position.

Finally, we need to create a WebSocket server on the server side to process and forward messages. Here is an example using Node.js and the WebSocket library:

const WebSocket = require('ws');

// 创建WebSocket服务器
const wss = new WebSocket.Server({ port: 3000 });

// 当有新的WebSocket连接建立时执行
wss.on('connection', function(ws) {
    console.log('有新的连接');

    // 当收到消息时执行
    ws.on('message', function(message) {
        console.log('收到消息: ' + message);

        // 将消息广播给所有连接的客户端
        wss.clients.forEach(function(client) {
            client.send(message);
        });
    });
});
Copy after login

In the above code, we have used the WebSocket library to create a WebSocket server. When a new connection is established, the connection event will be triggered. When a message is received, the message event will be triggered, and we will broadcast the received message to all connected clients.

With the above simple code example, we can implement a real-time chat room based on JavaScript. When the user enters a message and clicks the send button, the message is sent to the server through the WebSocket connection and forwarded by the server to all connected clients. After the client receives the message, it displays it in the UI interface. The whole process realizes the function of real-time communication.

Of course, the above example is just a simple implementation. In an actual real-time chat room, other functions such as disconnection and reconnection, user authentication, private chat, etc. need to be handled. I hope this article can provide you with a basic idea and code example to help you build your own real-time chat room.

The above is the detailed content of Build a real-time chat room based on JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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