PHP Logophpsocket.io/phpsocket.io

phpsocket.io/phpsocket.io is a PHP implementation that allows PHP applications to act as a server for the Socket.IO protocol. Socket.IO is a JavaScript library for real-time web applications. It enables bi-directional, event-based communication between web clients (browsers) and a server.

Traditionally, PHP is a stateless, request-response language, meaning a script executes, serves a response, and then terminates. This model is not suitable for persistent, real-time communication required by technologies like WebSockets or Socket.IO. phpsocket.io bridges this gap by providing a way for PHP to run as a long-lived process (daemon) that can maintain persistent connections with clients, listen for events, and emit events in real-time.

It leverages underlying PHP event-driven frameworks (like Workerman) to create a non-blocking server environment. This allows a PHP script to listen on a specific port, handle multiple client connections concurrently, and manage events such as 'connection', 'message', 'disconnect', or custom events defined by the application.

Key features and benefits:
* Real-time Communication: Enables instant updates, chat applications, gaming, notifications, and other interactive features.
* Event-driven: Communication is based on custom events, providing a flexible and decoupled architecture.
* Bi-directional: Both the client and server can send and receive messages.
* Broadcasting: Allows sending messages to all connected clients, clients in specific 'rooms', or individual clients.
* PHP Familiarity: Developers can use their existing PHP knowledge to build real-time backends without learning a new server-side language.

To use phpsocket.io, the PHP script must be executed via the command-line interface (CLI) and run indefinitely, typically managed by a process manager (e.g., Supervisor) to ensure it stays active. It is not designed to run within a traditional web server environment (like Apache or Nginx with PHP-FPM).

Example Code

```php
<?php
require __DIR__ . '/vendor/autoload.php';

use PHPSocketIO\SocketIO;

// Create a Socket.IO server instance on port 2020
// Clients will connect to ws://localhost:2020 or http://localhost:2020 (depending on transport)
$io = new SocketIO(2020);

// Event listener for a new client connection
$io->on('connection', function ($socket) use ($io) {
    echo "A user connected: " . $socket->id . "\n";

    // Listen for a 'chat message' event from the client
    $socket->on('chat message', function ($msg) use ($io, $socket) {
        echo "Received message from " . $socket->id . ": " . $msg . "\n";
        // Emit the 'chat message' event back to ALL connected clients
        $io->emit('chat message', $socket->id . ': ' . $msg);
    });

    // Listen for a 'disconnect' event from the client
    $socket->on('disconnect', function () {
        echo "A user disconnected.\n";
    });

    // You can also emit events directly to the connecting client
    $socket->emit('welcome', 'Welcome to the chat, ' . $socket->id . '!');
});

// Event listener for when a worker process starts
$io->on('workerStart', function () use ($io) {
    echo "Socket.IO server worker started on port 2020.\n";
    // You could set up database connections or other initializations here.
});

// Start the Socket.IO server. This will block and run indefinitely.
$io->start();

?>
```

To run this code:
1.  Install Composer if you haven't already.
2.  Create a project directory and navigate into it.
3.  Install phpsocket.io: `composer require phpsocket.io/phpsocket.io`
4.  Save the code above as `server.php` in your project directory.
5.  Run the server from your terminal: `php server.php`

Example Client-side (HTML/JavaScript) to connect to this server:
```html
<!DOCTYPE html>
<html>
<head>
    <title>Socket.IO Chat</title>
    <script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
    <style>
        body { font-family: sans-serif; }
        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages li { padding: 5px 10px; border-bottom: 1px solid #eee; }
        #messages li:nth-child(odd) { background: #eee; }
    </style>
</head>
<body>
    <h1>PHP Socket.IO Chat</h1>
    <ul id="messages"></ul>
    <form id="form" action="">
        <input id="m" autocomplete="off" /><button>Send</button>
    </form>

    <script>
        // Connect to your PHP Socket.IO server
        var socket = io('http://localhost:2020');

        var form = document.getElementById('form');
        var input = document.getElementById('m');
        var messages = document.getElementById('messages');

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            if (input.value) {
                // Emit a 'chat message' event to the server
                socket.emit('chat message', input.value);
                input.value = '';
            }
        });

        // Listen for 'chat message' events from the server
        socket.on('chat message', function(msg) {
            var item = document.createElement('li');
            item.textContent = msg;
            messages.appendChild(item);
            window.scrollTo(0, document.body.scrollHeight);
        });

        // Listen for the 'welcome' event from the server
        socket.on('welcome', function(msg) {
            console.log(msg); // Will show in browser console
            var item = document.createElement('li');
            item.textContent = '[SERVER] ' + msg;
            messages.appendChild(item);
            window.scrollTo(0, document.body.scrollHeight);
        });

        socket.on('connect', function() {
            console.log('Connected to server!');
        });

        socket.on('disconnect', function() {
            console.log('Disconnected from server!');
        });
    </script>
</body>
</html>
```