SlideShare a Scribd company logo
WebSockets with PHP:
Mission Impossible
Who am I?
✔ Yoan-Alexander Grigorov
✔ Proud PHP developer
✔ Likes to screw around with OOP
So what is a WebSocket after all?
WebSocket boosts UX
✔ Forget client pulls
✔ Forget long polling
✔ Make your application event based
What google say about
WebSockets:
✔ It's easy to build WebSocket server with node.js
✔ It's hard to build WebSocket server with PHP
Research! Research! Research!
Available tools for PHP
✔ Ratchet
✔ … it's only that. Seriously, it's only Ratchet
✔ Ok, there are some other libraries, all of them
named PHPWS
Ratchet
http://socketo.me
First things first
Install with composer
Setting up a server with Ratchet
<?php
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
class Handler implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {}
public function onMessage(ConnectionInterface $from, $msg) {}
public function onClose(ConnectionInterface $conn) {}
public function onError(ConnectionInterface $conn, Exception $e) {}
}
Setting up a server with Ratchet
<?php
use RatchetServerIoServer;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;
$handler = new AppHandler();
$server = IoServer::factory(
new HttpServer(new WsServer(
$handler
)
), 8123);
$server->run();
In the browser
var ws = new WebSocket('ws://127.0.0.1:8123');
// ... in some event
ws.send('Гледай кви ръки, чуек!');
// ... listener for messages:
ws.onmessage = function (message) {
alert(message);
};
Let's make a chat!
What do we need?
✔ Keep all active connection objects
✔ When a connection sends a message, notify all
others
✔ On disconnect – remove connection object from
the in-memory cache (map)
Connections handling
<?php
class Handler implements MessageComponentInterface {
private $connections = [];
public function onOpen(ConnectionInterface $conn) {
$this->connections[$conn->resourceId] = $conn;
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->connections as $receiver) {
$receiver->send($msg);
}
}
public function onClose(ConnectionInterface $conn) {
unset($this->connections[$conn->resourceId]);
}
}
That's it!
Keep an eye on:
✔ Run it like a daemon (/etc/init.d/skeleton)
✔ Fatal errors and exceptions – they kill the
daemon
✔ ORMs like Doctrine help you a lot
Doctrine uses Identity Map
Identity map gives you wings!
Web Servers and Web Sockets
Don't forget good old Ajax!
But how ajax could send messages
to the WebSocket server?
Message Queues
ZeroMQ
✔ Libzmq
✔ Has a PHP extension in PECL
✔ React/ZMQ (PHP wrapper)
✔ "react/zmq": "0.2.*|0.3.*" in Composer
What you need to know
✔ There are ZeroMQ listeners
– They use simple TCP
✔ There are ZeroMQ contexts (senders)
– They connect to ZeroMQ listeners and send
messages
What you need to know
✔ You need ZeroMQ listener in the WebSocket
daemon
✔ Ordinary PHP scripts send messages to the
listener
✔ Since ZeroMQ is in the WebSocket daemon, it
could easily interact with WebSocket
connections
Let's add ZeroMQ to our application!
Add callback for ZeroMQ messages
<?php
class Handler implements MessageComponentInterface
{
// ...
// this is CUSTOM method (not from interface)
public function onZMQMessage($message)
{
}
}
Add ZeroMQ listener to the daemon
<?php
use ...
$handler = new AppHandler();
$server = IoServer::factory(
new HttpServer(new WsServer(
$handler
)
), 8123);
// Listen on 127.0.0.1:4444
$context = new ReactZMQContext($server->loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind("tcp://127.0.0.1:4444");
$pull->on('message', function ($data) use ($handler) {
$handler->onZMQMessage($data);
});
$server->run();
In your Ajax server script
<?php
// ... add stuff to the database, other things...
// notify using ZeroMQ:
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'pusher');
$socket->connect("tcp://127.0.0.1:4444");
$socket->send('Глей кви ръки! Туй аз ли съм!?');
Go! Try it yourself!
Working code examples from this talk:
https://github.com/sasquatch-mc/ratchet-example
(check the branches)
References
✔ http://socketo.me
✔ http://zeromq.org
Thanks and good luck!
✔ joan.grigorov@gmail.com
✔ bgscripts.com

More Related Content

What's hot

Ethernet Shield
Ethernet ShieldEthernet Shield
Ethernet Shield
Tinker
 
nginxをソースからインストールしてみたよ
nginxをソースからインストールしてみたよnginxをソースからインストールしてみたよ
nginxをソースからインストールしてみたよmamoru tateoka
 
Implement server push in flask framework
Implement server push in flask frameworkImplement server push in flask framework
Implement server push in flask framework
Chi-Chia Huang
 
RabbitMQ for Perl mongers
RabbitMQ for Perl mongersRabbitMQ for Perl mongers
RabbitMQ for Perl mongers
Lenz Gschwendtner
 
Perl dancer
Perl dancerPerl dancer
Perl dancer
Marian Marinov
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
xSawyer
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Codemotion
 
Tools used for debugging
Tools used for debuggingTools used for debugging
Tools used for debugging
Marian Marinov
 
ZeroMQ: Super Sockets - by J2 Labs
ZeroMQ: Super Sockets - by J2 LabsZeroMQ: Super Sockets - by J2 Labs
ZeroMQ: Super Sockets - by J2 LabsJames Dennis
 
Event loop
Event loopEvent loop
Event loop
codepitbull
 
Puppet User Group Presentation - 15 March 2012
Puppet User Group Presentation - 15 March 2012Puppet User Group Presentation - 15 March 2012
Puppet User Group Presentation - 15 March 2012
Walter Heck
 
Vagrant - Version control your dev environment
Vagrant - Version control your dev environmentVagrant - Version control your dev environment
Vagrant - Version control your dev environment
bocribbz
 
Vagrant - Team Development made easy
Vagrant - Team Development made easyVagrant - Team Development made easy
Vagrant - Team Development made easy
Marco Silva
 
Pound & Varnish - Cache e Balanceamento de Carga
Pound & Varnish - Cache e Balanceamento de CargaPound & Varnish - Cache e Balanceamento de Carga
Pound & Varnish - Cache e Balanceamento de Carga
gsroma
 
tit
tittit
Introduction of Pharo 5.0
Introduction of Pharo 5.0Introduction of Pharo 5.0
Introduction of Pharo 5.0
Masashi Umezawa
 
Puppet and Openshift
Puppet and OpenshiftPuppet and Openshift
Puppet and Openshift
Gareth Rushgrove
 
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Codemotion
 
skipfish
skipfishskipfish

What's hot (20)

Ethernet Shield
Ethernet ShieldEthernet Shield
Ethernet Shield
 
nginxをソースからインストールしてみたよ
nginxをソースからインストールしてみたよnginxをソースからインストールしてみたよ
nginxをソースからインストールしてみたよ
 
Implement server push in flask framework
Implement server push in flask frameworkImplement server push in flask framework
Implement server push in flask framework
 
RabbitMQ for Perl mongers
RabbitMQ for Perl mongersRabbitMQ for Perl mongers
RabbitMQ for Perl mongers
 
Perl dancer
Perl dancerPerl dancer
Perl dancer
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
 
Tools used for debugging
Tools used for debuggingTools used for debugging
Tools used for debugging
 
ZeroMQ: Super Sockets - by J2 Labs
ZeroMQ: Super Sockets - by J2 LabsZeroMQ: Super Sockets - by J2 Labs
ZeroMQ: Super Sockets - by J2 Labs
 
Event loop
Event loopEvent loop
Event loop
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011Ferrara Linux Day 2011
Ferrara Linux Day 2011
 
Puppet User Group Presentation - 15 March 2012
Puppet User Group Presentation - 15 March 2012Puppet User Group Presentation - 15 March 2012
Puppet User Group Presentation - 15 March 2012
 
Vagrant - Version control your dev environment
Vagrant - Version control your dev environmentVagrant - Version control your dev environment
Vagrant - Version control your dev environment
 
Vagrant - Team Development made easy
Vagrant - Team Development made easyVagrant - Team Development made easy
Vagrant - Team Development made easy
 
Pound & Varnish - Cache e Balanceamento de Carga
Pound & Varnish - Cache e Balanceamento de CargaPound & Varnish - Cache e Balanceamento de Carga
Pound & Varnish - Cache e Balanceamento de Carga
 
tit
tittit
tit
 
Introduction of Pharo 5.0
Introduction of Pharo 5.0Introduction of Pharo 5.0
Introduction of Pharo 5.0
 
Puppet and Openshift
Puppet and OpenshiftPuppet and Openshift
Puppet and Openshift
 
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
 
skipfish
skipfishskipfish
skipfish
 

Viewers also liked

Asynchronous I/O in PHP
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHPThomas Weinert
 
Lindsay distributed geventzmq
Lindsay distributed geventzmqLindsay distributed geventzmq
Lindsay distributed geventzmqRobin Xiao
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
Wim Godden
 
A brief look inside UML
A brief look inside UMLA brief look inside UML
A brief look inside UML
Yoan-Alexander Grigorov
 
SOLID design
SOLID designSOLID design
Introduction to Domain-Driven Design
Introduction to Domain-Driven DesignIntroduction to Domain-Driven Design
Introduction to Domain-Driven Design
Yoan-Alexander Grigorov
 
Real-Time Web Apps & Symfony. What are your options?
Real-Time Web Apps & Symfony. What are your options?Real-Time Web Apps & Symfony. What are your options?
Real-Time Web Apps & Symfony. What are your options?
Phil Leggetter
 
React e Ratchet, async e websockets com PHP, por Gabriel Couto
React e Ratchet, async e websockets com PHP, por Gabriel CoutoReact e Ratchet, async e websockets com PHP, por Gabriel Couto
React e Ratchet, async e websockets com PHP, por Gabriel Couto
iMasters
 
Writing and using php streams and sockets
Writing and using php streams and socketsWriting and using php streams and sockets
Writing and using php streams and sockets
Elizabeth Smith
 
Asynchronous processing with PHP and Symfony2. Do it simple
Asynchronous processing with PHP and Symfony2. Do it simpleAsynchronous processing with PHP and Symfony2. Do it simple
Asynchronous processing with PHP and Symfony2. Do it simple
Kirill Chebunin
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Kacper Gunia
 
Websocket + Redis pubsub
Websocket + Redis pubsubWebsocket + Redis pubsub
Websocket + Redis pubsub
Kai Hsu
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
Ian Barber
 
Real Time Recommendations Using WebSockets and Redis - Ninad Divadkar, Inuit
Real Time Recommendations Using WebSockets and Redis - Ninad Divadkar, InuitReal Time Recommendations Using WebSockets and Redis - Ninad Divadkar, Inuit
Real Time Recommendations Using WebSockets and Redis - Ninad Divadkar, Inuit
Redis Labs
 
Pivot Tables
Pivot TablesPivot Tables
Pivot Tables
gjonesnemeth
 
MS Excel Pivot Table Reports & Charts
MS Excel Pivot Table Reports & ChartsMS Excel Pivot Table Reports & Charts
MS Excel Pivot Table Reports & Charts
dnbakhan
 
Zend Framework Push Notifications
Zend Framework Push NotificationsZend Framework Push Notifications
Zend Framework Push Notifications
Mike Willbanks
 

Viewers also liked (20)

ZeroMQ in PHP
ZeroMQ in PHPZeroMQ in PHP
ZeroMQ in PHP
 
Asynchronous I/O in PHP
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHP
 
Lindsay distributed geventzmq
Lindsay distributed geventzmqLindsay distributed geventzmq
Lindsay distributed geventzmq
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
A brief look inside UML
A brief look inside UMLA brief look inside UML
A brief look inside UML
 
SOLID design
SOLID designSOLID design
SOLID design
 
Introduction to Domain-Driven Design
Introduction to Domain-Driven DesignIntroduction to Domain-Driven Design
Introduction to Domain-Driven Design
 
Real-Time Web Apps & Symfony. What are your options?
Real-Time Web Apps & Symfony. What are your options?Real-Time Web Apps & Symfony. What are your options?
Real-Time Web Apps & Symfony. What are your options?
 
React e Ratchet, async e websockets com PHP, por Gabriel Couto
React e Ratchet, async e websockets com PHP, por Gabriel CoutoReact e Ratchet, async e websockets com PHP, por Gabriel Couto
React e Ratchet, async e websockets com PHP, por Gabriel Couto
 
Writing and using php streams and sockets
Writing and using php streams and socketsWriting and using php streams and sockets
Writing and using php streams and sockets
 
Asynchronous processing with PHP and Symfony2. Do it simple
Asynchronous processing with PHP and Symfony2. Do it simpleAsynchronous processing with PHP and Symfony2. Do it simple
Asynchronous processing with PHP and Symfony2. Do it simple
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
 
Websocket + Redis pubsub
Websocket + Redis pubsubWebsocket + Redis pubsub
Websocket + Redis pubsub
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
 
Real Time Recommendations Using WebSockets and Redis - Ninad Divadkar, Inuit
Real Time Recommendations Using WebSockets and Redis - Ninad Divadkar, InuitReal Time Recommendations Using WebSockets and Redis - Ninad Divadkar, Inuit
Real Time Recommendations Using WebSockets and Redis - Ninad Divadkar, Inuit
 
Tutorial pivot table
Tutorial pivot tableTutorial pivot table
Tutorial pivot table
 
Pivot Tables
Pivot TablesPivot Tables
Pivot Tables
 
Pivot Tables
Pivot TablesPivot Tables
Pivot Tables
 
MS Excel Pivot Table Reports & Charts
MS Excel Pivot Table Reports & ChartsMS Excel Pivot Table Reports & Charts
MS Excel Pivot Table Reports & Charts
 
Zend Framework Push Notifications
Zend Framework Push NotificationsZend Framework Push Notifications
Zend Framework Push Notifications
 

Similar to WebSockets with PHP: Mission impossible

Node js introduction
Node js introductionNode js introduction
Node js introduction
Joseph de Castelnau
 
Using Groovy to empower WebRTC Network Systems
Using Groovy to empower WebRTC Network SystemsUsing Groovy to empower WebRTC Network Systems
Using Groovy to empower WebRTC Network Systems
antonry
 
Nodejs
NodejsNodejs
Web socket with php v2
Web socket with php v2Web socket with php v2
Web socket with php v2
Leonardo Rifeli
 
OSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshopOSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshop
leffen
 
Why we choose Symfony2
Why we choose Symfony2Why we choose Symfony2
Why we choose Symfony2
Merixstudio
 
Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014
Stéphane Bégaudeau
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014
Stéphane Bégaudeau
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
Chris Cowan
 
Getting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGetting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.js
Grant Goodale
 
OSMC 2023 | IGNITE: Serving Server-Side WASM with Web Awareness with NGINX Un...
OSMC 2023 | IGNITE: Serving Server-Side WASM with Web Awareness with NGINX Un...OSMC 2023 | IGNITE: Serving Server-Side WASM with Web Awareness with NGINX Un...
OSMC 2023 | IGNITE: Serving Server-Side WASM with Web Awareness with NGINX Un...
NETWAYS
 
Madison PHP 2015 - DevOps For Small Teams
Madison PHP 2015 - DevOps For Small TeamsMadison PHP 2015 - DevOps For Small Teams
Madison PHP 2015 - DevOps For Small Teams
Joe Ferguson
 
Mazda siv - web services
Mazda   siv - web servicesMazda   siv - web services
Mazda siv - web services
Olivier Lépine
 
Developing and Deploying PHP with Docker
Developing and Deploying PHP with DockerDeveloping and Deploying PHP with Docker
Developing and Deploying PHP with DockerPatrick Mizer
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Aaron Rosenberg
 
Node Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup SlidesNode Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup SlidesMakoto Inoue
 
ZendCon 2015 - DevOps for Small Teams
ZendCon 2015 - DevOps for Small TeamsZendCon 2015 - DevOps for Small Teams
ZendCon 2015 - DevOps for Small Teams
Joe Ferguson
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
sametmax
 
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R..."Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
Fwdays
 

Similar to WebSockets with PHP: Mission impossible (20)

Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Using Groovy to empower WebRTC Network Systems
Using Groovy to empower WebRTC Network SystemsUsing Groovy to empower WebRTC Network Systems
Using Groovy to empower WebRTC Network Systems
 
Proposal
ProposalProposal
Proposal
 
Nodejs
NodejsNodejs
Nodejs
 
Web socket with php v2
Web socket with php v2Web socket with php v2
Web socket with php v2
 
OSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshopOSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshop
 
Why we choose Symfony2
Why we choose Symfony2Why we choose Symfony2
Why we choose Symfony2
 
Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Getting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGetting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.js
 
OSMC 2023 | IGNITE: Serving Server-Side WASM with Web Awareness with NGINX Un...
OSMC 2023 | IGNITE: Serving Server-Side WASM with Web Awareness with NGINX Un...OSMC 2023 | IGNITE: Serving Server-Side WASM with Web Awareness with NGINX Un...
OSMC 2023 | IGNITE: Serving Server-Side WASM with Web Awareness with NGINX Un...
 
Madison PHP 2015 - DevOps For Small Teams
Madison PHP 2015 - DevOps For Small TeamsMadison PHP 2015 - DevOps For Small Teams
Madison PHP 2015 - DevOps For Small Teams
 
Mazda siv - web services
Mazda   siv - web servicesMazda   siv - web services
Mazda siv - web services
 
Developing and Deploying PHP with Docker
Developing and Deploying PHP with DockerDeveloping and Deploying PHP with Docker
Developing and Deploying PHP with Docker
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup SlidesNode Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup Slides
 
ZendCon 2015 - DevOps for Small Teams
ZendCon 2015 - DevOps for Small TeamsZendCon 2015 - DevOps for Small Teams
ZendCon 2015 - DevOps for Small Teams
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
 
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R..."Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
 

Recently uploaded

top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 

Recently uploaded (20)

top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 

WebSockets with PHP: Mission impossible

  • 2. Who am I? ✔ Yoan-Alexander Grigorov ✔ Proud PHP developer ✔ Likes to screw around with OOP
  • 3. So what is a WebSocket after all?
  • 4.
  • 5. WebSocket boosts UX ✔ Forget client pulls ✔ Forget long polling ✔ Make your application event based
  • 6. What google say about WebSockets: ✔ It's easy to build WebSocket server with node.js ✔ It's hard to build WebSocket server with PHP
  • 8. Available tools for PHP ✔ Ratchet ✔ … it's only that. Seriously, it's only Ratchet ✔ Ok, there are some other libraries, all of them named PHPWS
  • 12. Setting up a server with Ratchet <?php use RatchetMessageComponentInterface; use RatchetConnectionInterface; class Handler implements MessageComponentInterface { public function onOpen(ConnectionInterface $conn) {} public function onMessage(ConnectionInterface $from, $msg) {} public function onClose(ConnectionInterface $conn) {} public function onError(ConnectionInterface $conn, Exception $e) {} }
  • 13. Setting up a server with Ratchet <?php use RatchetServerIoServer; use RatchetHttpHttpServer; use RatchetWebSocketWsServer; $handler = new AppHandler(); $server = IoServer::factory( new HttpServer(new WsServer( $handler ) ), 8123); $server->run();
  • 14. In the browser var ws = new WebSocket('ws://127.0.0.1:8123'); // ... in some event ws.send('Гледай кви ръки, чуек!'); // ... listener for messages: ws.onmessage = function (message) { alert(message); };
  • 15. Let's make a chat!
  • 16. What do we need? ✔ Keep all active connection objects ✔ When a connection sends a message, notify all others ✔ On disconnect – remove connection object from the in-memory cache (map)
  • 17. Connections handling <?php class Handler implements MessageComponentInterface { private $connections = []; public function onOpen(ConnectionInterface $conn) { $this->connections[$conn->resourceId] = $conn; } public function onMessage(ConnectionInterface $from, $msg) { foreach ($this->connections as $receiver) { $receiver->send($msg); } } public function onClose(ConnectionInterface $conn) { unset($this->connections[$conn->resourceId]); } }
  • 19. Keep an eye on: ✔ Run it like a daemon (/etc/init.d/skeleton) ✔ Fatal errors and exceptions – they kill the daemon ✔ ORMs like Doctrine help you a lot
  • 21.
  • 22. Identity map gives you wings!
  • 23. Web Servers and Web Sockets
  • 24. Don't forget good old Ajax!
  • 25. But how ajax could send messages to the WebSocket server?
  • 27.
  • 28. ZeroMQ ✔ Libzmq ✔ Has a PHP extension in PECL ✔ React/ZMQ (PHP wrapper) ✔ "react/zmq": "0.2.*|0.3.*" in Composer
  • 29. What you need to know ✔ There are ZeroMQ listeners – They use simple TCP ✔ There are ZeroMQ contexts (senders) – They connect to ZeroMQ listeners and send messages
  • 30. What you need to know ✔ You need ZeroMQ listener in the WebSocket daemon ✔ Ordinary PHP scripts send messages to the listener ✔ Since ZeroMQ is in the WebSocket daemon, it could easily interact with WebSocket connections
  • 31. Let's add ZeroMQ to our application!
  • 32. Add callback for ZeroMQ messages <?php class Handler implements MessageComponentInterface { // ... // this is CUSTOM method (not from interface) public function onZMQMessage($message) { } }
  • 33. Add ZeroMQ listener to the daemon <?php use ... $handler = new AppHandler(); $server = IoServer::factory( new HttpServer(new WsServer( $handler ) ), 8123); // Listen on 127.0.0.1:4444 $context = new ReactZMQContext($server->loop); $pull = $context->getSocket(ZMQ::SOCKET_PULL); $pull->bind("tcp://127.0.0.1:4444"); $pull->on('message', function ($data) use ($handler) { $handler->onZMQMessage($data); }); $server->run();
  • 34. In your Ajax server script <?php // ... add stuff to the database, other things... // notify using ZeroMQ: $context = new ZMQContext(); $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'pusher'); $socket->connect("tcp://127.0.0.1:4444"); $socket->send('Глей кви ръки! Туй аз ли съм!?');
  • 35. Go! Try it yourself!
  • 36. Working code examples from this talk: https://github.com/sasquatch-mc/ratchet-example (check the branches)
  • 38. Thanks and good luck! ✔ joan.grigorov@gmail.com ✔ bgscripts.com