open a websocket in php

To open a Websocket in PHP, you can use the Ratchet library which provides a set of tools to build Websocket applications.

Here is an example:

main.php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

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})\n";
    }

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

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

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

$server = \Ratchet\Server\IoServer::factory(
    new \Ratchet\Http\HttpServer(
        new \Ratchet\WebSocket\WsServer(
            new MyWebsocket()
        )
    ),
    8080
);

echo "Server started listening on *:8080\n";
$server->run();
1220 chars
48 lines

In this example, a new instance of the MyWebsocket class is created and passed to the IoServer object which starts to listen on port 8080. MyWebsocket implements the MessageComponentInterface interface which defines the methods to handle events like opening, closing, receiving a message, and errors.

To use this code, you need to install the Ratchet library using Composer:

main.php
composer require cboden/ratchet
32 chars
2 lines

Then you can execute the PHP script in the command line:

main.php
php my-websocket.php
21 chars
2 lines

gistlibby LogSnag