Home >Backend Development >PHP Tutorial >A complete tutorial on implementing real-time communication using PHP and Swoole

A complete tutorial on implementing real-time communication using PHP and Swoole

WBOY
WBOYOriginal
2023-06-28 08:12:061127browse

With the rapid development of Internet and mobile communication technology, real-time communication has attracted more and more attention. Real-time communication can realize instant messaging between users, online audio and video calls, game battles and other functions, bringing more possibilities to Internet applications.

This article will introduce how to use PHP and Swoole to achieve real-time communication. Starting from a simple WebSocket application, we will gradually introduce the basic knowledge of Socket programming and the application practice of Swoole. Reading this article requires basic knowledge of PHP basics and network programming.

1. WebSocket Basics

WebSocket is a two-way communication protocol based on the HTTP protocol. It uses a protocol called "handshake" to enable two-way communication. The advantage of WebSocket connection is that its overhead is very small, the real-time communication is very good, and two-way real-time communication can be established between the client and the server.

The establishment of WebSocket requires the following steps:

1. The browser initiates a WebSocket handshake request to the server. The request header contains some key fields, such as Upgrade, Connection, Sec-WebSocket -Key etc.

2. The server processes the client's WebSocket request and, if it meets the specification, returns a response message with fields such as Upgrade, Connection, and Sec-WebSocket-Accept in the response header.

3. The client receives the response message from the server, checks the Sec-WebSocket-Accept field, and confirms that the WebSocket handshake is successfully established.

4. Both parties can start data communication and can send text, binary, Ping, Pong and other messages.

Using WebSocket in PHP, we can implement it through the WebSocket service provided by Swoole. The following introduces the basic application of Swoole.

2. Swoole Basics

1. Install Swoole

Before starting to use Swoole, we need to install the Swoole extension on the server. You can install it with the following command:

pecl install swoole

or install it from the source code:

$ wget https://github.com/swoole/swoole-src/archive /v4.3.3.tar.gz
$ tar zxvf v4.3.3.tar.gz
$ cd swoole-src-4.3.3
$ phpize
$ ./configure
$ make && make install --with-swoole

  1. Swoole WebSocket service

Let’s implement a simple WebSocket service, listening to port 9501, when the client establishes a connection with the server When , send a hello message to the client.

<?php

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

$server->on('open', function (SwooleWebSocketServer $server, $request) {
    echo "new client connected
";
    $server->push($request->fd, "hello");
});

$server->on('message', function (SwooleWebSocketServer $server, $frame) {
    echo "received message: {$frame->data}
";
});

$server->start();

In this code, we create a new WebSocket server and listen on port 9501. When the client establishes a connection with the server, the open event is triggered and a hello message is sent to the client. When the client sends a message to the server, the message event is triggered, and we can output the information sent by the client through echo.

After starting the above code, we can use the browser or WebSocket client to connect to the server:

let ws = new WebSocket('ws://127.0.0.1:9501');
ws.onopen = function(event) {
    console.log('WebSocket connected');
};
ws.onmessage = function(event) {
    console.log('Received:', event.data);
};
ws.send('Hello, Server');

After the client successfully connects, the console will output the following information:

WebSocket connected
Received: hello

Indicates that the client has successfully received the hello message sent by the server.

3. Implement a real-time chat application

Next, let us implement a real-time chat application that allows multiple users to communicate in real-time in a chat room. This requires us to continue to expand the above WebSocket server to implement the basic functions of the chat room.

<?php

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

$server->set([
    'worker_num' => 2,    //启动2个Worker进程
]);

$server->on('open', function (SwooleWebSocketServer $server, $request) {
    echo "new client connected
";
    foreach($server->connections as $fd) {
        $server->push($fd, "{$request->fd} joined the room");
    }
});

$server->on('message', function (SwooleWebSocketServer $server, $frame) {
    foreach($server->connections as $fd) {
        if ($fd != $frame->fd) {
            $server->push($fd, "user {$frame->fd}: {$frame->data}");
        }
    }
});

$server->on('close', function ($server, $fd) {
    echo "client {$fd} closed
";
    foreach($server->connections as $fds) {
        $server->push($fds, "{$fd} quited the room");
    }
});

$server->start();

In the above code, we added handling of open and close events. When a user connects or closes the connection, messages to join or leave the chat room will be sent to other connected users. When a user sends a message in a chat room, the message is broadcast to other online users.

After starting the above code, we can use multiple browser windows to connect to the server separately and enter the same chat room. When a user sends a message, other users can receive the message in real time.

This article introduces how to use PHP and Swoole to achieve real-time communication, from basic WebSocket applications to real-time chat room applications. Swoole provides a more flexible asynchronous programming method, making it easier to write high-performance, high-concurrency, and low-latency applications.

The above is the detailed content of A complete tutorial on implementing real-time communication using PHP and Swoole. 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