Message withdrawal and revocation function of real-time chat system based on PHP

王林
Release: 2023-08-26 09:18:01
Original
1137 people have browsed it

Message withdrawal and revocation function of real-time chat system based on PHP

Message withdrawal and revocation function of real-time chat system based on PHP

Introduction:
With the rapid development and popularity of the Internet, real-time chat system has become a daily important way of communication. When developing a chat system, implementing message recall and revocation functions is a common requirement. This article will introduce how to use PHP to write a real-time chat system based on WebSocket and implement message withdrawal and revocation functions.

  1. Build the environment
    First, we need to set up the PHP environment and WebSocket service. You can choose to use a PHP framework such as Laravel or Symfony, or directly use PHP's native WebSocket library. In the framework, you can use Composer to manage dependencies.
  2. Create database
    We need a database to store chat messages. MySQL or other relational databases can be used. Create a table named chat_messages with the following fields:
  3. id: The unique identifier of the message
  4. sender_id: The user ID of the sender
  5. receiver_id: The user of the receiver ID
  6. message: Message content
  7. timestamp: Message sending time
  8. Real-time chat function
    Use WebSocket protocol to achieve real-time communication. In PHP, a WebSocket server can be implemented using libraries such as Ratchet or Swoole. By listening to the client's messages and connection events, the messages are saved to the database and sent to the recipient in real time.

The following is a simple example using the Ratchet library:

require 'vendor/autoload.php';

use RatchetMessageComponentInterface;
use RatchetConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;

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

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        // 解析接收到的消息
        $data = json_decode($msg, true);

        // 将消息保存到数据库
        $message = new ChatMessage();
        $message->sender_id = $data['sender_id'];
        $message->receiver_id = $data['receiver_id'];
        $message->message = $data['message'];
        $message->timestamp = time();
        $message->save();

        // 将消息发送给接收者
        foreach ($this->clients as $client) {
            if ($client !== $from && $client->resourceId == $data['receiver_id']) {
                $client->send($data['message']);
                break;
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, Exception $e) {
        $conn->close();
    }
}

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

$server->run();
Copy after login
  1. Implementing the message withdrawal and revocation function
    In order to implement the message withdrawal and revocation function, we need to implement the message withdrawal and revocation function in the database Add a column to the table to identify the status of the message. You can add a field named status to indicate the status of the message:
  2. 1: Normal
  3. 2: Withdrawn
  4. 3: Withdrawn

Modify the onMessage function and add the setting of the status field before saving the message to the database:

$message = new ChatMessage();
$message->sender_id = $data['sender_id'];
$message->receiver_id = $data['receiver_id'];
$message->message = $data['message'];
$message->timestamp = time();
$message->status = 1; // 设置消息状态为正常
$message->save();
Copy after login

To implement the withdrawal function, the client can send a withdrawal instruction to the server and set the corresponding message status to withdrawal:

public function onMessage(ConnectionInterface $from, $msg) {
    // 解析接收到的消息
    $data = json_decode($msg, true);

    // 根据消息ID更新状态为撤回
    ChatMessage::where('id', $data['message_id'])
        ->update(['status' => 2]);

    // 广播撤回消息给接收者
    $this->broadcastMessage($data['message_id'], $from, $data['receiver_id']);
}

public function broadcastMessage($messageId, ConnectionInterface $from, $receiverId) {
    foreach ($this->clients as $client) {
        if ($client !== $from && $client->resourceId == $receiverId) {
            $client->send(json_encode(['action' => 'revoke', 'message_id' => $messageId]));
            break;
        }
    }
}
Copy after login

To implement the revocation function, you can send a revocation instruction to the server on the client side, and set the corresponding message status to revocation:

public function onMessage(ConnectionInterface $from, $msg) {
    // 解析接收到的消息
    $data = json_decode($msg, true);

    // 根据消息ID更新状态为撤销
    ChatMessage::where('id', $data['message_id'])
        ->update(['status' => 3]);

    // 广播撤销消息给接收者
    $this->broadcastMessage($data['message_id'], $from, $data['receiver_id']);
}

public function broadcastMessage($messageId, ConnectionInterface $from, $receiverId) {
    foreach ($this->clients as $client) {
        if ($client !== $from && $client->resourceId == $receiverId) {
            $client->send(json_encode(['action' => 'revoke', 'message_id' => $messageId]));
            break;
        }
    }
}
Copy after login
  1. Client processing
    On the client side , appropriately display whether the message has been withdrawn or revoked based on the returned message status.

Summary:
This article introduces how to use PHP to build a real-time chat system based on WebSocket and implement message withdrawal and revocation functions. These features can be easily implemented by using the Ratchet library and database to store and process messages. In actual projects, corresponding expansion and optimization can be carried out according to needs.

The above is the detailed content of Message withdrawal and revocation function of real-time chat system based on PHP. 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!