Home  >  Article  >  Backend Development  >  Use php to develop Websocket to implement real-time push function

Use php to develop Websocket to implement real-time push function

王林
王林Original
2023-12-02 12:44:24849browse

Use php to develop Websocket to implement real-time push function

Title: Use PHP to develop Websocket to achieve real-time push function

Websocket is a communication protocol based on TCP protocol. In Web development, Websocket can be used to achieve real-time push Push function to achieve real-time communication or real-time data update needs. In this article, we will develop a Websocket server using PHP language and provide specific code examples.

1. Overview

Websocket is a full-duplex communication protocol. Compared with the traditional HTTP protocol, Websocket is more suitable for real-time communication scenarios. Features of the Websocket protocol include:

  1. Supports full-duplex communication and can send and receive data at the same time.
  2. Compatible with HTTP protocol, uses HTTP-like handshake protocol for connection establishment, and can communicate through HTTP/HTTPS port.
  3. Data can be sent at any time without waiting for the request-response cycle.
  4. Supports cross-domain communication and can communicate under different domain names.

2. Development environment preparation

Before starting development, you need to prepare some tools and environment:

  1. Install PHP: Make sure you have A PHP interpreter is installed.
  2. Install Composer: Composer is a dependency management tool for PHP. We will use it to install Websocket-related libraries.
  3. Choose an editor: You can choose any editor you like for development, such as VS Code, Sublime Text, etc.

3. Install the Websocket library

In PHP, there are many mature Websocket libraries to choose from, among which the more commonly used ones are Ratchet, Swoole, etc. In this article, we will use Ratchet for development.

  1. Create a composer.json file in the project root directory and add the following content:
{
    "require": {
        "cboden/ratchet": "^0.4"
    }
}
  1. Open the terminal and switch to In the project root directory, execute the following command to install the Ratchet library:
composer install

4. Write the Websocket server code

Before creating the Websocket server, let us first discuss the workflow of Websocket.

  1. Connection establishment: The client establishes a Websocket connection with the server. The client sends an HTTP request, and the server returns a protocol switching response to establish the connection.
  2. Message transmission: Both parties can send messages through the send method and receive messages through the onMessage event.
  3. Connection closure: Either the client or the server sends a close frame to close the connection.

The following is a sample code for writing a Websocket server using the Ratchet library:

<?php

use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;
use RatchetServerIoServer;

require 'vendor/autoload.php';

class MyWebSocket 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) {
        // 处理接收到的消息逻辑
        foreach ($this->clients as $client) {
            if ($client !== $from) {
                $client->send($msg);
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection closed: {$conn->resourceId}
";
    }

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

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new MyWebSocket()
        )
    ),
    8080
);

$server->run();

The above code defines a MyWebSocket class that implements MessageComponentInterfaceMethods in the interface are used to handle connection, message, shutdown and error events. In the onOpen event, we add the newly established connection to the $clients collection; in the onMessage event, we traverse all connections and send the message to other clients; in the onClose event, we delete the closed connection from the $clients collection; in the onError event, we handle the exception and close the connection .

5. Run the Websocket server

Switch to the project root directory in the terminal and execute the following command to start the Websocket server:

php server.php

If everything is normal, you will see something like The following output:

New connection: 1
New connection: 2
Message received: Hello from client 1
Message received: Hello from client 2
Connection closed: 1

6. Write client code

Finally, we need to write a client for testing.

<!DOCTYPE html>
<html>
<head>
    <title>Websocket Client</title>
    <script>
        var socket = new WebSocket("ws://localhost:8080");

        socket.onopen = function() {
            console.log("Connected");
        };

        socket.onmessage = function(event) {
            console.log("Message received: " + event.data);
        };

        socket.onclose = function(event) {
            console.log("Connection closed");
        };

        function sendMessage() {
            var message = document.getElementById("message").value;
            socket.send(message);
        }
    </script>
</head>
<body>
    <input type="text" id="message">
    <button onclick="sendMessage()">Send</button>
</body>
</html>

In this example, we use JavaScript to create a Websocket connection and print the corresponding logs when the connection is established, messages are received, and the connection is closed. On the page, we provide an input box and a send button for sending messages.

7. Summary

This article introduces the method of developing Websocket server using PHP, and provides specific code examples to help readers understand the working principle and usage of Websocket. Websocket has real-time communication capabilities and can be used to implement real-time push, chat rooms, multiplayer games and other scenarios. I hope this article will be helpful to you.

The above is the detailed content of Use php to develop Websocket to implement real-time push function. 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