SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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...
 

Kürzlich hochgeladen

Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 

Kürzlich hochgeladen (20)

Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 

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