亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

PHP調(diào)用Workerman5.0實(shí)現(xiàn)一對(duì)一聊天

 更新時(shí)間:2025年03月21日 15:20:14   作者:Ai 編碼  
這篇文章主要介紹了實(shí)現(xiàn)一對(duì)一聊天功能的相關(guān)代碼,本文將使用 Workerman 5.0 作為后端,使用WebSocket在前端進(jìn)行通信,有需要的小伙伴可以參考一下

要實(shí)現(xiàn)一對(duì)一聊天功能,使用 Workerman 5.0 作為后端,前端可以使用 WebSocket 進(jìn)行通信。以下是實(shí)現(xiàn)步驟和代碼示例。

1. 安裝 Workerman

首先,確保你已經(jīng)安裝了 Workerman??梢酝ㄟ^(guò) Composer 安裝:

composer require workerman/workerman

2. 后端代碼

創(chuàng)建一個(gè) PHP 文件(例如 chat_server.php),用于處理 WebSocket 連接和消息傳遞。

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;
use Workerman\Connection\TcpConnection;

// 創(chuàng)建一個(gè) WebSocket 服務(wù)器
$ws_worker = new Worker("websocket://0.0.0.0:2346");

// 保存用戶連接的數(shù)組
$users = [];

// 當(dāng)有客戶端連接時(shí)
$ws_worker->onConnect = function(TcpConnection $connection) use (&$users) {
    echo "New connection\n";
};

// 當(dāng)有客戶端發(fā)送消息時(shí)
$ws_worker->onMessage = function(TcpConnection $connection, $data) use (&$users) {
    $message = json_decode($data, true);

    if (isset($message['type'])) {
        switch ($message['type']) {
            case 'login':
                // 用戶登錄,保存連接
                $users[$message['user_id']] = $connection;
                $connection->user_id = $message['user_id'];
                echo "User {$message['user_id']} logged in\n";
                break;

            case 'chat':
                // 一對(duì)一聊天
                if (isset($users[$message['to_user_id']])) {
                    $users[$message['to_user_id']]->send(json_encode([
                        'type' => 'chat',
                        'from_user_id' => $connection->user_id,
                        'message' => $message['message']
                    ));
                }
                break;
        }
    }
};

// 當(dāng)客戶端斷開(kāi)連接時(shí)
$ws_worker->onClose = function(TcpConnection $connection) use (&$users) {
    if (isset($connection->user_id)) {
        unset($users[$connection->user_id]);
        echo "User {$connection->user_id} disconnected\n";
    }
};

// 運(yùn)行 worker
Worker::runAll();

3. 前端代碼

在前端,使用 WebSocket 連接到服務(wù)器,并實(shí)現(xiàn)登錄和發(fā)送消息的功能。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
</head>
<body>
    <div>
        <input type="text" id="user_id" placeholder="Your User ID">
        <button onclick="login()">Login</button>
    </div>
    <div>
        <input type="text" id="to_user_id" placeholder="To User ID">
        <input type="text" id="message" placeholder="Message">
        <button onclick="sendMessage()">Send</button>
    </div>
    <div id="chat"></div>

    <script>
        let ws;
        let user_id;

        function login() {
            user_id = document.getElementById('user_id').value;
            ws = new WebSocket('ws://127.0.0.1:2346');

            ws.onopen = function() {
                ws.send(JSON.stringify({
                    type: 'login',
                    user_id: user_id
                }));
            };

            ws.onmessage = function(event) {
                const message = JSON.parse(event.data);
                if (message.type === 'chat') {
                    document.getElementById('chat').innerHTML += `<p>From ${message.from_user_id}: ${message.message}</p>`;
                }
            };
        }

        function sendMessage() {
            const to_user_id = document.getElementById('to_user_id').value;
            const message = document.getElementById('message').value;
            ws.send(JSON.stringify({
                type: 'chat',
                to_user_id: to_user_id,
                message: message
            }));
        }
    </script>
</body>
</html>

4. 運(yùn)行服務(wù)器

在終端中運(yùn)行 PHP 文件啟動(dòng) WebSocket 服務(wù)器:

php chat_server.php start

5. 測(cè)試

打開(kāi)兩個(gè)瀏覽器窗口,分別輸入不同的用戶 ID 并登錄。

在一個(gè)窗口中輸入目標(biāo)用戶 ID 和消息,點(diǎn)擊發(fā)送。

另一個(gè)窗口應(yīng)該會(huì)收到消息并顯示在頁(yè)面上。

總結(jié)

通過(guò)以上步驟,你可以實(shí)現(xiàn)一個(gè)簡(jiǎn)單的一對(duì)一聊天系統(tǒng)。Workerman 作為后端處理 WebSocket 連接和消息傳遞,前端通過(guò) WebSocket 與服務(wù)器通信,實(shí)現(xiàn)實(shí)時(shí)聊天功能。

到此這篇關(guān)于PHP調(diào)用Workerman5.0實(shí)現(xiàn)一對(duì)一聊天的文章就介紹到這了,更多相關(guān)PHP Workerman聊天內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論