Home Backend Development PHP Tutorial Group chat and private chat functions of real-time chat system based on PHP

Group chat and private chat functions of real-time chat system based on PHP

Aug 27, 2023 pm 02:43 PM
php live chat Group chat private chat

Group chat and private chat functions of real-time chat system based on PHP

Group chat and private chat functions of real-time chat system based on PHP

With the development of the Internet, real-time chat systems have become more and more important in our daily lives. is becoming more and more important. Whether you are chatting with friends on social media platforms or communicating with colleagues at work, live chat systems play an important role. This article will introduce how to use PHP to develop a real-time chat-based system that supports group chat and private chat functions.

First, we need to set up a server to handle real-time chat requests. We use PHP and WebSocket to implement this functionality. WebSocket is a TCP-based protocol that allows full-duplex communication between the browser and the server. In PHP, we can use the Ratchet library to create a WebSocket server.

First, we need to install the Ratchet library. Run the following command in the terminal:

composer require cboden/ratchet
Copy after login

Once the installation is complete, we can create a file named server.php and write the following code in it:

<?php
require 'vendor/autoload.php';

use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
use RatchetWebSocketWsServer;
use RatchetHttpHttpServer;
use RatchetServerIoServer;
use RatchetWampWampServerProtocol;

class Chat implements MessageComponentInterface
{
    protected $clients;

    public function __construct()
    {
        $this->clients = new SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})
";
    }

    public function onMessage(ConnectionInterface $from, $msg)
    {
        // 处理客户端发送的消息
        $data = json_decode($msg);
        $type = $data->type;

        switch ($type) {
            case 'register':
                $from->username = $data->username;
                echo "User registered: " . $from->username . "
";
                break;
            case 'group':
                $message = $data->message;
                $this->broadcastMessage($from, $message);
                break;
            case 'private':
                $recipient = $data->recipient;
                $message = $data->message;
                $this->sendPrivateMessage($from, $recipient, $message);
                break;
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected
";
    }

    public function onError(ConnectionInterface $conn, Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}
";
        $conn->close();
    }

    public function broadcastMessage($from, $message)
    {
        foreach ($this->clients as $client) {
            if ($client !== $from) {
                $client->send($message);
            }
        }
    }

    public function sendPrivateMessage($from, $recipient, $message)
    {
        foreach ($this->clients as $client) {
            if ($client->username == $recipient) {
                $client->send($message);
                $from->send($message);
                break;
            }
        }
    }
}

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8080
);

$server->run();
Copy after login

In the above code, we created a class named Chat to handle operations such as connecting, sending messages, and closing connections. In the onMessage method, we perform different operations based on the message type. If the type is register, it means there is a user registration connection; if the type is group, it means there is a user sending a group message; if the type is private, it means there is a user Send a private message. We use the broadcastMessage method to broadcast group messages and the sendPrivateMessage method to send private messages.

Next, we can create a file called index.html and write the following code in it:

<!DOCTYPE html>
<html>
<head>
    <title>Chat</title>
</head>
<body>
    <input type="text" id="username" placeholder="Username"><br>
    <input type="text" id="message" placeholder="Message"><br>
    <button onclick="register()">Register</button>
    <button onclick="sendGroupMessage()">Send Group Message</button>
    <button onclick="sendPrivateMessage()">Send Private Message</button>

    <script>
        var conn = new WebSocket('ws://localhost:8080');

        conn.onopen = function(e) {
            console.log("Connection established!");
        };

        conn.onmessage = function(e) {
            var chatbox = document.getElementById("chatbox");
            chatbox.innerHTML += e.data + "<br>";
        };

        function register() {
            var username = document.getElementById("username").value;
            var data = {
                type: 'register',
                username: username
            };
            conn.send(JSON.stringify(data));
        }

        function sendGroupMessage() {
            var message = document.getElementById("message").value;
            var data = {
                type: 'group',
                message: message
            };
            conn.send(JSON.stringify(data));
        }

        function sendPrivateMessage() {
            var recipient = document.getElementById("username").value;
            var message = document.getElementById("message").value;
            var data = {
                type: 'private',
                recipient: recipient,
                message: message
            };
            conn.send(JSON.stringify(data));
        }
    </script>
</body>
</html>
Copy after login

In the above code, we create a WebSocket connects and registers the connection callback function. In the register function we send the username to the server for registration. In the sendGroupMessage function, we send the group message to the server, and the server will broadcast the message to all users. In the sendPrivateMessage function, we send the private message to the specified user.

Now, we can run the php server.php command in the terminal to start the server. Then, we can open the index.html file in the browser, enter the user name and click the registration button. Next, we can enter a message and click the send button to have a group chat or private chat. The server broadcasts the corresponding message to other users or sends it to a specified user.

Summary:
This article introduces how to use PHP and WebSocket to develop a real-time chat system and implement group chat and private chat functions. By creating a WebSocket server and communicating with it, we are able to get and send messages from other users in real time. With a simple code example, we implemented a basic real-time chat system. By extending the code, we can implement more functions, such as adding user verification, chat record storage, etc.

The above is the detailed content of Group chat and private chat functions of real-time chat system based on PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the host see private chat messages in Tencent meetings? Can the host see private chat messages in Tencent meetings? Feb 18, 2024 am 11:12 AM

Can Tencent Meeting private chats be seen by the host? With the rise of remote working and online meetings, various video conferencing tools have become more and more popular. As one of China's leading video conferencing tools, Tencent Conference has always attracted much attention. One of the important features is private chat, which allows participants to communicate privately during the meeting. However, many people are worried about whether the content of private chats will be seen by the moderator. This article will analyze the mechanism of Tencent’s conference private chat function and answer this question. First, we need to understand the basic operations of Tencent meeting private chat

Can the host of Tencent Conference private chat see it? Can the host of Tencent Conference private chat see it? Feb 20, 2024 pm 04:06 PM

Can the host of Tencent Conference Private Chat see it? With the development of technology, online conferencing has become an important way for modern people to work, study, and communicate. Among many online conferencing platforms, Tencent Conference is popular among users for its stability, ease of use and rich functions. When conducting a Tencent meeting, sometimes there is a need for private chat, or for some private communication with the host (or other participants). So, when conducting private chats in Tencent meetings, can the host see the content of these private chats? This is a question that many users are concerned about. firstly, I

How to chat privately on Xianyu? List of methods to chat privately with sellers How to chat privately on Xianyu? List of methods to chat privately with sellers Mar 12, 2024 pm 03:00 PM

When we use this platform, we can all make better choices, especially when we know the details of the products we want, we can chat with each other privately. These methods are relatively simple, so Don't worry, don't panic. Some private chat methods are relatively simple. We usually use these methods directly to understand the details of the product or bargain, but it is also to solve the problem of users. All kinds of doubts are also to bring you some corresponding content choices, so today the editor will explain to you how to conduct private chat. Friends who don’t know yet must not miss it. Hurry up and take a look with the editor, don’t miss it.​

How to recover deleted records from TikTok private chats How to recover deleted records from TikTok private chats May 07, 2024 am 11:00 AM

1. After deleting Douyin private message chat history, it is usually impossible to directly restore it. 2. However, you can contact Douyin official to try to communicate the possibility of recovery. 3. Open the Douyin app, enter the "Me" page, click on the three horizontal bars in the upper right corner, and select "Settings" > "About Douyin". 4. Find and call the "Customer Service Hotline" or contact Douyin official via official email to inquire about the possibility of restoring chat records.

Using PHP to implement behavior logs and operation records of real-time chat function Using PHP to implement behavior logs and operation records of real-time chat function Aug 26, 2023 pm 06:34 PM

Behavior logs and operation records using PHP to implement real-time chat function Introduction: Real-time chat function has become one of the standard features of many websites and applications. However, to ensure the stability and security of the chat system, it is necessary to record user behaviors and operations for troubleshooting and user tracking. This article will introduce how to use PHP to implement behavior logs and operation records of real-time chat functions. We will use a simple example to illustrate the specific implementation process. Step 1: Set up the database First, we need to create a database for storing behavior logs

Use PHP to implement scheduled messages and scheduled tasks for real-time chat function Use PHP to implement scheduled messages and scheduled tasks for real-time chat function Aug 26, 2023 am 09:28 AM

Use PHP to implement scheduled messages and scheduled tasks for real-time chat function. With the rapid development of the Internet, real-time communication has become an important way for people to communicate. In order to enrich users' interactive experience, many websites and applications have added real-time chat functions. This article will introduce how to use PHP to implement scheduled messages and scheduled tasks in the real-time chat function. 1. Implementation of scheduled messages Scheduled messages refer to sending messages to specified users at specified points in time. PHP can use timers to achieve this function. Below is a simple sample code

How to privately message the seller in Zhuanzhuan How to privately message the seller in Zhuanzhuan How to privately message the seller in Zhuanzhuan How to privately message the seller in Zhuanzhuan Mar 26, 2024 am 09:41 AM

The functions here are super powerful, and you can directly log in to your account to use them. There are a lot of product types here, so you can choose at will and find your favorite treasures. Of course, some of your own You can also choose to publish unused items for sale, which is super convenient and everyone’s needs can be met. Of course, if you see some better products, you will want to send a private message to the seller to have some discussions about the products. To help you get these products better, and for friends who don’t know how to send private messages to sellers, let’s take a look at the following method. How to send a private message to the seller in Zhuanzhuan: 1. First open Zhuanzhuan 2. Click the search box, enter the user’s nickname, check the user and search 3. Enter his personal homepage

Use PHP to implement anonymous chat and encrypted transmission of real-time chat function Use PHP to implement anonymous chat and encrypted transmission of real-time chat function Aug 14, 2023 pm 04:34 PM

Using PHP to realize anonymous chat and encrypted transmission of real-time chat function. With the development of the Internet, the way of communication between people has also undergone earth-shaking changes. Among them, the live chat function has become an increasingly popular method of communication. For many websites, providing anonymous chat functions can attract more users to participate, but the security and privacy of user information also need to be taken into consideration. This article will explore how to use PHP to implement anonymous chat and encrypted transmission of real-time chat function, and provide code samples for reference. 1. Anonymous chat is implemented in Anonymous

See all articles