Home > PHP Framework > Workerman > body text

How to implement the barrage function of the online chat system based on Workerman

王林
Release: 2023-09-08 09:09:22
Original
867 people have browsed it

How to implement the barrage function of the online chat system based on Workerman

How to implement the barrage function of the online chat system based on Workerman

With the development of the Internet and the popularity of social media, barrage has become an increasingly popular A welcome form of interaction. Danmaku refers to the display of user-entered messages in a scrolling form on a video or chat interface. Using the barrage function in a chat room can enhance the user's interactive experience and make the chat more interesting and lively. This article will introduce how to implement the barrage function of the online chat system based on Workerman, and attach corresponding code examples.

1. Environment preparation

Before we start, we need to ensure that we have the following environment and tools:

  1. PHP environment: Workerman is a high-performance PHP-based TCP/UDP communication framework, so the PHP environment needs to be prepared in advance. You can use integrated environments such as XAMPP or WAMP, or you can build your own PHP environment.
  2. workerman framework: Before starting, you need to install the workerman framework. You can install it through composer, or download the latest version of workerman directly from GitHub.

2. Create a basic chat room

First, we need to create a basic chat room and use the workerman framework to handle client connections and message sending.

  1. Create chat room server
require_once __DIR__ . '/vendor/autoload.php';

use WorkermanWorker;

$worker = new Worker("websocket://0.0.0.0:8080");

$worker->onWorkerStart = function($worker) {
    echo "Chat room started
";
};

$worker->onConnect = function($connection) {
    echo "New connection
";
};

$worker->onMessage = function($connection, $data) {
    echo "Received message: " . $data . "
";
    $connection->send("Hello, " . $data);
};

Worker::runAll();
Copy after login

In the above code, we created a basic workerman server and listened to port 8080. When a new connection is established, the onConnect callback function will be executed. When a message sent by the client is received, the onMessage callback function will be executed.

  1. Create client page
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Chat Room</title>
</head>
<body>
    <input type="text" id="message" placeholder="Input your message">
    <button onclick="sendMessage()">Send</button>

    <script>
        var socket = new WebSocket("ws://127.0.0.1:8080");
        socket.onopen = function() {
            console.log("Connected to server");
        };

        function sendMessage() {
            var message = document.getElementById("message").value;
            socket.send(message);

            document.getElementById("message").value = "";
        };

        socket.onmessage = function(event) {
            var message = event.data;
            console.log("Received message: " + message);
        };
    </script>
</body>
</html>
Copy after login

In the above code, we created a simple chat room client page. The user can enter a message in the input box and send it to the server by clicking the "Send" button. When a message is received from the server, it is displayed in the browser's console.

3. Implement the barrage function

To implement the barrage function, we need to make appropriate modifications to the chat room server and client codes. Here is the sample code:

  1. Modify the chat room server
// 添加一个数组来保存接收到的消息
$messages = [];

$worker->onMessage = function($connection, $data) use (&$messages) {
    $messages[] = $data;
    foreach ($worker->connections as $client) {
        // 向所有客户端广播弹幕消息
        $client->send($data);
    }
    echo "Received message: " . $data . "
";
};
Copy after login

In the above code, we have added an array $messages to save the received messages. When a new message is received, we save it in an array and send the message to all clients through a loop.

  1. Modify the client page
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Chat Room with Danmaku</title>
    <style>
        .danmaku {
            position: absolute;
            font-size: 20px;
            color: red;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <input type="text" id="message" placeholder="Input your message">
    <button onclick="sendMessage()">Send</button>

    <script>
        var socket = new WebSocket("ws://127.0.0.1:8080");
        var danmakus = [];

        socket.onopen = function() {
            console.log("Connected to server");
        };

        function sendMessage() {
            var message = document.getElementById("message").value;
            socket.send(message);

            document.getElementById("message").value = "";
        };

        socket.onmessage = function(event) {
            var message = event.data;
            console.log("Received message: " + message);

            // 创建一个新的弹幕
            var danmaku = document.createElement("div");
            danmaku.textContent = message;
            danmaku.className = "danmaku";

            // 设置弹幕的起始位置和动画效果
            danmaku.style.top = Math.floor(Math.random() * (window.innerHeight - 30)) + "px";
            danmaku.style.left = window.innerWidth + "px";
            danmaku.style.animationDuration = (Math.random() * 10 + 5) + "s";

            // 添加弹幕到页面
            document.body.appendChild(danmaku);

            // 添加弹幕到数组
            danmakus.push(danmaku);

            // 监听弹幕动画结束事件,删除已经播放完成的弹幕
            danmaku.addEventListener("animationend", function() {
                document.body.removeChild(danmaku);
                danmakus.splice(danmakus.indexOf(danmaku), 1);
            });

            // 避免弹幕过多导致页面卡顿,最多显示10条弹幕
            if (danmakus.length > 10) {
                var removedDanmaku = danmakus.shift();
                document.body.removeChild(removedDanmaku);
            }
        };
    </script>
</body>
</html>
Copy after login

In the above code, we added a style sheet to set the style of the barrage. When receiving the message, we create a new barrage element and set its animation effect, starting position and text. Then add the barrages to the page and retain an array of barrages to manage the playback order of the barrages. In order to avoid page lag, we limit the display of up to 10 bullet chats and remove them from the page and array when the bullet chat animation ends.

4. Run and test

  1. Start the chat room server

Enter the directory where the chat room server is located on the command line and execute the following command:

php chat_room.php start
Copy after login
  1. Open the client page

Open the client page in the browser, enter the message and click the send button. The chat room server will send the received message to all connected clients and display it on the page as a barrage.

Summary

This article introduces how to implement the barrage function of the online chat system based on Workerman. By adding the corresponding code and style sheet, we can implement the function of receiving and displaying barrage messages. Such barrage function can improve the interactivity and fun of chat rooms, making users more active and engaged. I hope the sample code in this article can help readers quickly implement their own chat room barrage function.

The above is the detailed content of How to implement the barrage function of the online chat system based on Workerman. 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!