Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
PHP Reactive Programming

You're reading from   PHP Reactive Programming Build fault tolerant and high performing application in PHP based on the reactive architecture

Arrow left icon
Product type Paperback
Published in Mar 2017
Publisher Packt
ISBN-13 9781786462879
Length 364 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Martin Sikora Martin Sikora
Author Profile Icon Martin Sikora
Martin Sikora
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Introduction to Reactive Programming 2. Reactive Programming with RxPHP FREE CHAPTER 3. Writing a Reddit Reader with RxPHP 4. Reactive versus a Typical Event-Driven Approach 5. Testing RxPHP Code 6. PHP Streams API and Higher-Order Observables 7. Implementing Socket IPC and WebSocket Server/Client 8. Multicasting in RxPHP and PHP7 pthreads Extension 9. Multithreaded and Distributed Computing with pthreads and Gearman 10. Using Advanced Operators and Techniques in RxPHP Appendix. Reusing RxPHP Techniques in RxJS

Implementing a WebSocket server


To implement a WebSocket server, we'll use a library called cboden/ratchet:

$ composer require cboden/ratchet

A WebSocket server is represented by a class implementing the MessageComponentInterface interface with four methods onOpen(), onClose(), onError(), and onMessage(). How this class behaves on each of the events is up to the developer. Usually in chat applications, we want to keep all active connections in an array of clients and read messages, with onMessage() to resend them to all clients.

We'll first implement only the required methods and then add some custom ones as well:

// ChatServer.php 
use Ratchet\MessageComponentInterface; 
use Ratchet\ConnectionInterface; 
 
class ChatServer implements MessageComponentInterface { 
  private $connections; 
  private $history = []; 
  private $subject; 
 
  public function __construct() { 
    $this->subject = new Subject(); 
  } 
 
  public...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime