Practical application of WebSocket technology in online chat rooms

WBOY
Release: 2023-10-15 11:50:02
Original
1239 people have browsed it

Practical application of WebSocket technology in online chat rooms

Practical application of WebSocket technology in online chat rooms

With the rapid development of the Internet, people's demand for instant messaging is getting higher and higher. Although the traditional HTTP protocol can transmit data, it needs to initiate a request every time, which is inefficient. In order to solve this problem, WebSocket technology came into being. WebSocket technology can establish a persistent, two-way communication channel between the browser and the server, greatly improving the efficiency and real-time performance of data transmission, so it has been widely used in online chat rooms.

Advantages of WebSocket:

  1. Lower latency: Compared with the traditional HTTP request-response model, WebSocket technology can establish a persistent connection, achieve instant communication, and can achieve faster communication. Send chat content to other users.
  2. Less network traffic: WebSocket technology transfers data multiple times by establishing a connection instead of sending an HTTP request each time. This reduces the number of packets and reduces network traffic.
  3. Better compatibility: The standard of WebSocket technology has matured and is widely supported by modern browsers without the need for additional plug-ins or libraries.

The following takes an online chat room as an example to introduce the practical application of WebSocket technology.

First, on the server side, we use Node.js as the backend language. The advantage of using Node.js is that you can use JavaScript language for development, which facilitates interaction with the front end.

//引入WebSocket模块
const WebSocket = require('ws');

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

//保存连接的用户
const users = new Set();

//WebSocket服务端启动成功后的回调函数
wss.on('listening', () => {
  console.log('WebSocket server is running on port 3000.');
});

//处理WebSocket连接
wss.on('connection', (ws) => {
  //将新用户添加到用户列表中
  users.add(ws);

  //监听消息事件
  ws.on('message', (message) => {
    //将消息发送给其他用户
    users.forEach((user) => {
      if (user !== ws) {
        user.send(message);
      }
    });
  });

  //监听连接关闭事件
  ws.on('close', () => {
    //将用户从用户列表中移除
    users.delete(ws);
  });
});
Copy after login

On the client side, we use HTML, CSS, and JavaScript to implement the user interface and communicate with the server.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>在线聊天室</title>
  <style>
    #chat { width: 400px; height: 300px; margin-bottom: 10px; overflow-y: auto; }
  </style>
</head>
<body>
  <div id="chat"></div>
  <input type="text" id="message" placeholder="请输入消息">
  <button id="send">发送</button>

  <script>
    const chat = document.getElementById('chat');
    const messageInput = document.getElementById('message');
    const sendButton = document.getElementById('send');

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

    //监听WebSocket连接成功事件
    ws.addEventListener('open', () => {
      console.log('WebSocket connection is established.');
    });

    //监听WebSocket接收到消息事件
    ws.addEventListener('message', (event) => {
      const message = event.data;
      const messageNode = document.createElement('p');
      messageNode.textContent = message;
      chat.appendChild(messageNode);
    });

    //发送消息
    sendButton.addEventListener('click', () => {
      const message = messageInput.value;
      ws.send(message);
      messageInput.value = '';
    });
  </script>
</body>
</html>
Copy after login

The above code implements a simple online chat room. When a user accesses a page through a browser, a WebSocket connection is established and the message entered by the user is sent to the server. The server will forward the received messages to other connected users, thus realizing the real-time chat function.

Through WebSocket technology, the practical application of online chat rooms is realized. WebSocket's two-way communication can effectively reduce time delay and network traffic, providing a better user experience. As WebSocket technology continues to develop and improve, I believe it will be applied and promoted in more fields.

The above is the detailed content of Practical application of WebSocket technology in online chat rooms. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!