Home  >  Article  >  Backend Development  >  How to communicate in real time with WebSocket protocol via PHP

How to communicate in real time with WebSocket protocol via PHP

王林
王林Original
2023-07-29 22:04:541932browse

How to communicate in real time through PHP and WebSocket protocol

With the development of Web applications, real-time communication has become very important in many scenarios, such as online chat, stock quotes, etc. The WebSocket protocol is designed to establish a real-time communication connection between a web browser and a server. This article will introduce how to use PHP and WebSocket protocols for real-time communication and provide relevant code examples.

1. Introduction to WebSocket protocol
The WebSocket protocol is a full-duplex communication protocol based on the TCP protocol. It can enable the server to actively push messages to the client and receive messages from the client. Compared with the traditional HTTP protocol, the WebSocket protocol has the following characteristics:

  1. Real-time two-way communication: WebSocket can achieve real-time two-way communication between the server and the client, without the client constantly polling the server.
  2. Lower communication overhead: Compared with the HTTP protocol, the WebSocket protocol has smaller communication headers, which reduces communication overhead.
  3. Higher performance: Because the WebSocket protocol can establish long connections, it reduces the handshake overhead of each request, thereby improving communication performance.

2. PHP WebSocket extension
PHP officially does not provide direct support for WebSocket, but you can implement WebSocket functions by installing and using extensions. Currently, the more commonly used PHP WebSocket extensions include the following:

  1. Ratchet: A lightweight PHP WebSocket library that provides support for WebSocket servers and clients, is easy to use and has comprehensive functions.
  2. Swoole: A high-performance PHP network communication library that can implement WebSocket server and client.
  3. Workerman: A multi-threaded PHP Socket framework that supports WebSocket servers and clients.

Due to space limitations, this article will use Ratchet extension as an example for demonstration.

3. Install the Ratchet extension
You can install the Ratchet extension through Composer, execute the following command to install:

composer require cboden/ratchet

4. Create a WebSocket server
The following is a simple WebSocket Server-side implementation can return the received message to the client as it is:

<?php
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;

require 'vendor/autoload.php';

class MyWebSocketServer implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            $client->send($msg);
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, Exception $e) {
        echo "Error: {$e->getMessage()}
";
        $conn->close();
    }
}

$server = App::make('RatchetServerIoServer', [
    new AppMyWebSocketServer()
]);

$server->run();

5. Create WebSocket client
The following is a simple WebSocket client implementation that can communicate with the above-mentioned server:

<?php
use RatchetClientWebSocket;
use RatchetClientConnector;
use ReactEventLoopFactory as EventLoopFactory;

require 'vendor/autoload.php';

$loop = EventLoopFactory::create();
$connector = new Connector($loop);

$connector('ws://localhost:8000')->then(function (WebSocket $conn) {
    $conn->on('message', function ($msg) use ($conn) {
        echo "Received: {$msg}
";
        $conn->close();
    });

    $conn->send('Hello, WebSocket Server!');
}, function (Exception $e) use ($loop) {
    echo "Could not connect: {$e->getMessage()}
";
    $loop->stop();
});

$loop->run();

6. Run the WebSocket service
Start the WebSocket server through the command line:

php server.php

Then execute the client code:

php client.php

You can realize the client and service end-to-end real-time communication.

Summary:
This article briefly introduces how to use PHP and WebSocket protocols for real-time communication, and provides relevant code examples of Ratchet extensions. Through the WebSocket protocol, we can implement the server to actively push messages to the client and achieve real-time two-way communication. Using the PHP WebSocket extension, we can easily create WebSocket servers and clients and achieve real-time communication through simple code.

The above is the detailed content of How to communicate in real time with WebSocket protocol via PHP. 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