Home >Backend Development >PHP Tutorial >How to use PHP and swoole to build a highly available online consultation platform?

How to use PHP and swoole to build a highly available online consultation platform?

PHPz
PHPzOriginal
2023-07-21 10:33:091460browse

How to use PHP and swoole to build a highly available online consultation platform?

In today’s Internet era, online consulting platforms are becoming the first choice for more and more companies and individuals. In order to provide efficient and stable online consultation services, we can use PHP and swoole to build a highly available online consultation platform.

1. Preparation

Before you start, make sure you have installed PHP and swoole extensions. You can install the swoole extension through the following command:

pecl install swoole

2. Create a database

First, we need to create a database to store user information, chat records and other data. You can use the following SQL statements to create databases and tables:

CREATE DATABASE online_consulting;
USE online_consulting;

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL
);

CREATE TABLE messages (
    id INT PRIMARY KEY AUTO_INCREMENT,
    sender_id INT NOT NULL,
    receiver_id INT NOT NULL,
    message VARCHAR(255) NOT NULL,
    timestamp INT NOT NULL
);

3. Build the server

Create a file named server.php as our server code. The following is a simple example:

<?php

$server = new SwooleWebSocketServer('0.0.0.0', 9501);

$server->on('open', function ($server, $request) {
    echo "New client connected: {$request->fd}
";
});

$server->on('message', function ($server, $frame) {
    $data = json_decode($frame->data, true);

    switch ($data['type']) {
        case 'login':
            // 处理登录逻辑
            break;

        case 'message':
            // 处理消息逻辑
            break;
    }
});

$server->on('close', function ($server, $fd) {
    echo "Client disconnected: {$fd}
";
});

$server->start();

4. Processing login logic

On the server side, we need to process the user's login logic. When a user sends a login request, we need to verify the username and password and return a corresponding response based on the verification results. The following is a simple example:

// 登录逻辑
function handleLogin($server, $frame, $data) {
    $username = $data['username'];
    $password = $data['password'];

    // 从数据库中查询用户信息
    $user = queryUserByUsername($username);

    if (!$user || $user['password'] !== $password) {
        // 登录失败
        $response = [
            'type' => 'login',
            'success' => false,
            'message' => 'Invalid username or password'
        ];
    } else {
        // 登录成功
        $response = [
            'type' => 'login',
            'success' => true,
            'message' => 'Login successful'
        ];
    }

    $server->push($frame->fd, json_encode($response));
}

5. Processing message logic

When a user sends a message, we need to save the message to the database and send it to the corresponding recipient. The following is a simple example:

// 消息逻辑
function handleMessage($server, $frame, $data) {
    $senderId = $data['sender_id'];
    $receiverId = $data['receiver_id'];
    $message = $data['message'];
    $timestamp = time();

    // 将消息保存到数据库
    saveMessage($senderId, $receiverId, $message, $timestamp);

    // 发送消息给接收者
    $receiverFd = getUserFdById($receiverId);

    if ($receiverFd !== null) {
        $response = [
            'type' => 'message',
            'sender_id' => $senderId,
            'receiver_id' => $receiverId,
            'message' => $message,
            'timestamp' => $timestamp
        ];

        $server->push($receiverFd, json_encode($response));
    }
}

6. Client interaction

Finally, we need to use JavaScript to write a client page to interact with the server. The following is a simple example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Online Consulting Platform</title>
</head>
<body>
    <input type="text" id="username" placeholder="Username">
    <input type="password" id="password" placeholder="Password">
    <button onclick="login()">Login</button>

    <input type="text" id="message" placeholder="Message">
    <button onclick="sendMessage()">Send</button>

    <ul id="messages"></ul>

    <script>
        const socket = new WebSocket('ws://localhost:9501');

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

        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);

            switch (data.type) {
                case 'login':
                    if (data.success) {
                        console.log('Login successful');
                    } else {
                        console.log('Login failed: ' + data.message);
                    }
                    break;

                case 'message':
                    const li = document.createElement('li');
                    li.innerHTML = data.sender_id + ': ' + data.message;
                    document.getElementById('messages').appendChild(li);
                    break;
            }
        };

        function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            const data = {
                type: 'login',
                username: username,
                password: password
            };

            socket.send(JSON.stringify(data));
        }

        function sendMessage() {
            const senderId = 1; // 从数据库中获取当前用户ID
            const receiverId = 2; // 从数据库中获取接收者ID
            const message = document.getElementById('message').value;

            const data = {
                type: 'message',
                sender_id: senderId,
                receiver_id: receiverId,
                message: message
            };

            socket.send(JSON.stringify(data));
        }
    </script>
</body>
</html>

Through the above steps, we have completed the main code examples required to build a highly available online consultation platform using PHP and swoole. You can further improve the functions according to actual needs and add some necessary security verification measures to ensure the stability and security of the platform.

The above is the detailed content of How to use PHP and swoole to build a highly available online consultation platform?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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