Creating a WebSocket server in PHP
Is it possible ?

Stéphane Hulard

Consultant, Trainer, Contributor.

WebSockets ?

Standard real-time protocol

RFC6455 released in 2011

Full-Duplex: Client to server and server to client

« Just » a protocol, language agnostic

Only transfer data when useful ≠ polling

A persistent connection

Different paradigm, different problems

Memory management, long running process, shared state between clients…

Real world usage ?

Retrieve sensor data,

Chat and social feeds,

Collaborative editing/coding,

Gaming…

A chat with Ratchet

WebSocket server and client written in PHP

Built using ReactPHP ecosystem

ReactPHP ?  

Event-driven,non-blocking I/Owith PHP

                            // 🤓 Low level libraries
                        

You say EventLoop ?

Waits for and dispatches events or messages.

                            $loop = React\EventLoop\Factory::create();

// Register streams to listen on

$loop->run();
                        

Non blocking streams ?

Everywhere,for everything…

                            $stdin  = new React\Stream\ReadableResourceStream(STDIN,  $loop);
$stdout = new React\Stream\WritableResourceStream(STDOUT, $loop);
                        

Go back to Ratchet…

Two libraries: client and server.

                            # Server only
composer require cboden/ratchet

# Client only
composer require ratchet/pawl
                        

Some specifications

Client must connect to Server

Client messages are sent to other connected clients.

Client can define his name to identify himself.

👾 Let's look the code!

🔗 https://github.com/shulard/ipc-websocket-sample

What to do now ?

Learn to run PHP workers !

A bit different than the Request / Response model.

👉 Use tools like Supervisor or SystemD.

Don't rush on WebSockets !

Do you really need Full-Duplex?

👉 For Server to Client only, check Server-Sent Events!

Advantages to do it in PHP ?

Sharing code,domain expertise,team knowledge…

@s_hulard

https://github.com/shulard/ipc-websocket-sample