>  기사  >  PHP 프레임워크  >  ThinkPHP6 채팅방 개발 가이드: 실시간 통신 기능 구현

ThinkPHP6 채팅방 개발 가이드: 실시간 통신 기능 구현

WBOY
WBOY원래의
2023-08-12 14:31:471211검색

ThinkPHP6 채팅방 개발 가이드: 실시간 통신 기능 구현

ThinkPHP6 채팅방 개발 가이드: 실시간 커뮤니케이션 기능 구현

소개:
인터넷의 급속한 발전과 함께 실시간 커뮤니케이션에 대한 수요도 늘어나고 있습니다. 실시간 소통의 일반적인 방법으로 채팅방은 폭넓은 관심과 활용을 받아왔습니다. 이 기사에서는 ThinkPHP6 프레임워크를 사용하여 실시간 통신 기능을 구현하는 간단하고 빠른 방법을 제공합니다.

1. 환경 구성:
시작하기 전에 개발 환경을 구성해야 합니다. PHP 및 ThinkPHP6 프레임워크가 설치되어 있는지 확인하세요. 동시에 이 기사에서는 MySQL 데이터베이스를 사용하므로 MySQL을 올바르게 설치하고 구성했는지도 확인해야 합니다.

2. 데이터베이스 및 테이블 만들기:
먼저 chatroom이라는 데이터베이스를 만듭니다. 그런 다음 메시지라는 테이블을 만들어 채팅 메시지를 저장합니다. 테이블 구조는 다음과 같습니다:

CREATE TABLE `messages` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `content` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

3. 컨트롤러 및 뷰 작성:
다음으로 채팅방 관련 로직을 처리하기 위해 채팅방 컨트롤러를 생성해야 합니다. app/controller 디렉토리에 Chatroom.php를 생성하고 다음 코드를 추가합니다:

<?php
namespace appcontroller;

use thinkacadeView;
use GatewayWorkerLibGateway;

class Chatroom
{
    public function index()
    {
        return View::fetch('index');
    }

    public function sendMessage()
    {
        $content = input('post.content');
        $data = [
            'content' => $content,
            'created_at' => date('Y-m-d H:i:s')
        ];
            hinkacadeDb::name('messages')->insert($data);
        Gateway::sendToAll(json_encode($data));
    }
}

app/view 디렉토리에 index.html을 생성하고 다음 코드를 추가합니다:

<!DOCTYPE html>
<html>
<head>
    <title>聊天室</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div>
        <textarea id="message" style="width: 300px; height: 100px;"></textarea>
        <button onclick="sendMessage()">发送</button>
    </div>
    <div id="chatContent"></div>
</body>
<script>
    var websocket = new WebSocket('ws://localhost:8282');
    websocket.onopen = function () {
        console.log('连接成功');
    };
    websocket.onmessage = function (evt) {
        var message = JSON.parse(evt.data);
        $('#chatContent').append('<p>' + message.content + ' - ' + message.created_at + '</p>');
    };
    websocket.onerror = function () {
        console.log('连接失败');
    };
    websocket.onclose = function () {
        console.log('断开连接');
    };

    function sendMessage() {
        var content = $('#message').val();
        $.ajax({
            type: 'POST',
            url: '<?php echo url("Chatroom/sendMessage"); ?>',
            data: {content: content},
            success: function () {
                $('#message').val('');
            },
            error: function () {
                alert('发送失败');
            }
        });
    }
</script>
</html>

4. WebSocket 서비스를 시작합니다:
ThinkPHP6가 통합되지 않았습니다. 기본적으로 WebSocket 서비스를 구현하려면 GatewayWorker 확장을 사용해야 합니다. 먼저 GatewayWorker 확장을 설치해야 합니다.

composer require workerman/gatewayworker

그런 다음 프로젝트 루트 디렉터리에 start.php를 만들고 다음 코드를 추가합니다.

<?php
use thinkacadeDb;
use WorkermanWorker;
use GatewayWorkerGateway;

require __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:8282');
$worker->name = 'ChatroomGateway';
$worker->count = 1;

$worker->onWorkerStart = function () {
    Gateway::$registerAddress = '127.0.0.1:1238';
    Gateway::onConnect(function ($connection) {
        $messages = Db::name('messages')->select();
        Gateway::sendToCurrentClient(json_encode($messages));
    });
    Gateway::onMessage(function ($connection, $data) {
        Gateway::sendToAll($data);
    });
};

Worker::runAll();

그런 다음 명령줄에서 다음 명령을 실행하여 WebSocket 서비스를 시작합니다.

php start.php start

5. 완료 :
이제 http://localhost/chatroom/index.html에 접속하시면 채팅방을 이용하실 수 있습니다. 메시지를 입력하고 보내기를 클릭하면 실시간으로 메시지를 보내고 받을 수 있습니다.

결론:
이 글의 가이드를 통해 ThinkPHP6 프레임워크와 GatewayWorker 확장을 사용하여 간단한 채팅방을 성공적으로 구현했습니다. 이 기사가 독자들에게 실시간 통신 기능을 신속하게 구현하는 데 도움이 되는 몇 가지 유용한 참고 자료를 제공할 수 있기를 바랍니다. 그러나 이 기사는 단순한 예일 뿐이라는 점에 유의해야 합니다. 실제 프로젝트에서는 특정 요구에 따라 확장하고 최적화해야 합니다.

위 내용은 ThinkPHP6 채팅방 개발 가이드: 실시간 통신 기능 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.