PHP 기반의 실시간 채팅 시스템의 그룹 채팅 및 비공개 채팅 기능

王林
풀어 주다: 2023-08-27 14:44:01
원래의
881명이 탐색했습니다.

PHP 기반의 실시간 채팅 시스템의 그룹 채팅 및 비공개 채팅 기능

PHP 기반 실시간 채팅 시스템의 그룹 채팅 및 비공개 채팅 기능

인터넷의 발달과 함께 실시간 채팅 시스템은 우리 일상생활에서 점점 더 중요해지고 있습니다. 소셜 미디어 플랫폼에서 친구들과 채팅을 하거나 직장 동료와 소통할 때 라이브 채팅 시스템은 중요한 역할을 합니다. 이 기사에서는 PHP를 사용하여 그룹 채팅 및 개인 채팅 기능을 지원하는 실시간 채팅 기반 시스템을 개발하는 방법을 소개합니다.

먼저 실시간 채팅 요청을 처리할 서버를 설정해야 합니다. 우리는 이 기능을 구현하기 위해 PHP와 WebSocket을 사용합니다. WebSocket은 브라우저와 서버 간의 전이중 통신을 허용하는 TCP 기반 프로토콜입니다. PHP에서는 Ratchet 라이브러리를 사용하여 WebSocket 서버를 만들 수 있습니다.

먼저 Ratchet 라이브러리를 설치해야 합니다. 터미널에서 다음 명령을 실행하세요.

composer require cboden/ratchet
로그인 후 복사

설치가 완료된 후 server.php라는 파일을 만들고 그 안에 다음 코드를 작성할 수 있습니다. server.php的文件,并在其中编写以下代码:

<?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();
로그인 후 복사

在上述代码中,我们创建了一个名为Chat的类来处理连接、发送消息和关闭连接等操作。在onMessage方法中,我们根据消息类型来执行不同的操作。如果类型是register,表示有用户注册连接;如果类型是group,表示有用户发送群组消息;如果类型是private,表示有用户发送私聊消息。我们使用broadcastMessage方法来广播群组消息,使用sendPrivateMessage方法来发送私聊消息。

接下来,我们可以创建一个名为index.html的文件,并在其中编写以下代码:

<!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>
로그인 후 복사

在上述代码中,我们创建了一个WebSocket连接并注册了连接的回调函数。在register函数中,我们将用户名发送到服务器以进行注册。在sendGroupMessage函数中,我们将群组消息发送到服务器,服务器会将消息广播给所有用户。在sendPrivateMessage函数中,我们将私聊消息发送给指定用户。

现在,我们可以在终端中运行php server.php命令来启动服务器。然后,我们可以在浏览器中打开index.htmlrrreee

위 코드에서 우리는 create 연결, 메시지 보내기, 연결 닫기 등의 작업을 처리하기 위해 Chat이라는 클래스가 생성됩니다. onMessage 메서드에서는 메시지 유형에 따라 다양한 작업을 수행합니다. 유형이 register이면 사용자가 연결을 등록했음을 의미하고, 유형이 group이면 사용자가 그룹 메시지를 보냈음을 의미합니다. 비공개입니다. 사용자가 비공개 메시지를 보냈음을 나타냅니다. broadcastMessage 메서드를 사용하여 그룹 메시지를 브로드캐스트하고 sendPrivateMessage 메서드를 사용하여 비공개 메시지를 보냅니다.


다음으로 index.html이라는 파일을 생성하고 그 안에 다음 코드를 작성하면 됩니다.

rrreee🎜위 코드에서는 WebSocket 연결을 생성하고 연결 콜백을 등록합니다. register 함수에서는 등록을 위해 사용자 이름을 서버로 보냅니다. sendGroupMessage 함수에서는 그룹 메시지를 서버로 보내고, 서버는 메시지를 모든 사용자에게 브로드캐스팅합니다. sendPrivateMessage 함수에서는 지정된 사용자에게 비공개 메시지를 보냅니다. 🎜🎜이제 터미널에서 php server.php 명령을 실행하여 서버를 시작할 수 있습니다. 그런 다음 브라우저에서 index.html 파일을 열고 사용자 이름을 입력한 후 등록 버튼을 클릭하면 됩니다. 다음으로 메시지를 입력하고 보내기 버튼을 클릭하여 그룹 채팅이나 개인 채팅을 할 수 있습니다. 서버는 해당 메시지를 다른 사용자에게 브로드캐스트하거나 지정된 사용자에게 보냅니다. 🎜🎜요약: 🎜이 글에서는 PHP와 WebSocket을 사용하여 실시간 채팅 시스템을 개발하고 그룹 채팅 및 비공개 채팅 기능을 구현하는 방법을 소개합니다. WebSocket 서버를 생성하고 통신함으로써 우리는 실시간으로 다른 사용자로부터 메시지를 받고 보낼 수 있습니다. 간단한 코드 예시를 통해 기본적인 실시간 채팅 시스템을 구현했습니다. 코드를 확장하면 사용자 인증 추가, 채팅 기록 저장 등 더 많은 기능을 구현할 수 있습니다. 🎜

위 내용은 PHP 기반의 실시간 채팅 시스템의 그룹 채팅 및 비공개 채팅 기능의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!