SlideShare a Scribd company logo
1 of 38
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 ShieldTinker
 
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 frameworkChi-Chia Huang
 
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 2017Codemotion
 
Tools used for debugging
Tools used for debuggingTools used for debugging
Tools used for debuggingMarian 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
 
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 2012Walter Heck
 
Vagrant - Version control your dev environment
Vagrant - Version control your dev environmentVagrant - Version control your dev environment
Vagrant - Version control your dev environmentbocribbz
 
Vagrant - Team Development made easy
Vagrant - Team Development made easyVagrant - Team Development made easy
Vagrant - Team Development made easyMarco 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 Cargagsroma
 
Introduction of Pharo 5.0
Introduction of Pharo 5.0Introduction of Pharo 5.0
Introduction of Pharo 5.0Masashi Umezawa
 
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
 

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 PHPWim Godden
 
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 CoutoiMasters
 
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 socketsElizabeth 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 simpleKirill 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 MeetupKacper Gunia
 
Websocket + Redis pubsub
Websocket + Redis pubsubWebsocket + Redis pubsub
Websocket + Redis pubsubKai Hsu
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The AnswerIan 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, InuitRedis Labs
 
MS Excel Pivot Table Reports & Charts
MS Excel Pivot Table Reports & ChartsMS Excel Pivot Table Reports & Charts
MS Excel Pivot Table Reports & Chartsdnbakhan
 
Zend Framework Push Notifications
Zend Framework Push NotificationsZend Framework Push Notifications
Zend Framework Push NotificationsMike 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

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 Systemsantonry
 
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 workshopleffen
 
Why we choose Symfony2
Why we choose Symfony2Why we choose Symfony2
Why we choose Symfony2Merixstudio
 
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 2014Sté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 2014Stéphane Bégaudeau
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris 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.jsGrant 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 TeamsJoe Ferguson
 
Mazda siv - web services
Mazda   siv - web servicesMazda   siv - web services
Mazda siv - web servicesOlivier 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
 
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 TeamsJoe 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 Websocketsametmax
 
"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

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Recently uploaded (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

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