PHP WebSocket development examples: practical examples of how to implement specific functions

WBOY
Release: 2023-09-12 13:30:01
Original
1314 people have browsed it

PHP WebSocket开发实例:如何实现特定功能的实践案例

PHP WebSocket development examples: practical cases of how to implement specific functions

In recent years, with the increasing complexity of Web applications, the traditional HTTP protocol has become less effective in real-time communication Showed some shortcomings. In order to meet the needs of real-time communication, WebSocket came into being.

WebSocket is a protocol for full-duplex communication over a single TCP connection, which allows the server to actively push data to the client without the client sending a request. This makes real-time communication, online games, real-time monitoring and other applications more convenient and efficient.

In this article, we will introduce an example of WebSocket development based on PHP. Through this case, we will learn the practical process of how to implement a specific function.

Suppose we want to develop an online chat room application. Users can send messages on the web page, and other users can receive and reply immediately. This function involves the following key points:

  1. Building the WebSocket server
  2. Communication between the client and the server
  3. Sending and receiving messages
  4. User List Maintenance

First, we need to build a WebSocket server. In PHP, we can use the Ratchet library to implement WebSocket functions. Install Ratchet through Composer:

composer require cboden/ratchet
Copy after login

Next, create a server.php file and write the following code:

<?php

require 'vendor/autoload.php';

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

class Chat 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 {$conn->resourceId} has disconnected
";
    }
    
    public function onError(ConnectionInterface $conn, Exception $e) {
        echo "An error has occurred: {$e->getMessage()}
";
        $conn->close();
    }
}

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

$server->run();
Copy after login

This code creates a Chat class and implements the MessageComponentInterface interface. We can define various Event handler function. Next, we need to send the message to other online users. Here we use a foreach loop to traverse all connected clients and determine whether it is the source client itself.

Run php server.php in the command line, and the WebSocket server will be started.

Next, we need to implement communication with the server on the web page. On a web page, we can use JavaScript to create a WebSocket object to communicate with the backend.

<script>
var conn = new WebSocket('ws://localhost:8080');

conn.onopen = function() {
    console.log('Connected!');
}

conn.onmessage = function(e) {
    console.log('Received: ' + e.data);
}

function sendMessage() {
    var message = document.getElementById('input').value;
    conn.send(message);
}
</script>
Copy after login

The above code creates a WebSocket object and defines the handler functions for onopen and onmessage events. After entering the message in the input box, click the send button to call the sendMessage function to send the message to the server.

Finally, we need to maintain a user list to display online users and update the user list. We can add corresponding logic to the onOpen and onClose events on the server side:

public function onOpen(ConnectionInterface $conn) {
    $this->clients->attach($conn);
    echo "New connection! ({$conn->resourceId})
";
    
    // 将新用户加入用户列表,并广播给其他在线用户
    foreach ($this->clients as $client) {
        $client->send('New user has joined');
    }
}

public function onClose(ConnectionInterface $conn) {
    $this->clients->detach($conn);
    echo "Connection {$conn->resourceId} has disconnected
";
    
    // 将离线用户从用户列表中删除,并广播给其他在线用户
    foreach ($this->clients as $client) {
        $client->send('A user has left');
    }
}
Copy after login

Through the above code, when new users join and users go offline, we will broadcast corresponding messages to other online users to update the user list .

In summary, we have learned how to use PHP WebSocket to implement the development process of specific functions through an example of an online chat room. Of course, WebSocket can also be used in a wider range of fields, such as push notifications, online games, real-time monitoring, etc. I hope the practical cases in this article can be helpful to your learning and development!

The above is the detailed content of PHP WebSocket development examples: practical examples of how to implement specific functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!