Desenvolvendo
aplicações real-time
com PHP
PHPEXPERIENCE 2019
EDUARDO CESAR
ZARP
Mas o que é uma aplicação ‘real time’ ?!
...Processamento real time está presente nos
mais diversos tipos de sistemas das mais
variadas indústrias...
Mas e quando pensamos na web...
HTTP
Long Pooling
Long Pooling
O servidor não responde solicitações de imediato
mantendo-a como pendente do ponto de vista do
cliente.
HTTP Streaming
HTTP Streaming
O servidor mantém a solicitação no estado aberto
indefinidamente, ou seja, mesmo após o envio de
informações nenhuma indicação de que resposta foi
concluída é emitida.
Alguns problemas comuns em ambas as
abordagens
Excesso de requisições desnecessárias
Recursos que não estão em uso
Latência de resposta
OH, e agora quem poderá nos ajudar???
WEBSOCKETS
WebSocket é uma tecnologia que permite a
comunicação bidirecional por canais full-duplex
sobre um único soquete Transmission Control
Protocol (TCP).
Comunicação bidirecional full duplex
Algumas de suas características são:
URIs, Handshake, Interface
URI
Handshake
E O PHP???
<?php
$address = '0.0.0.0';
$port = 3030;
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $address, $port);
socket_listen($server);
$client = socket_accept($server);
$request = socket_read($client, 5000);
<?php
$headers = "HTTP/1.1 101 Switching Protocolsrn";
$headers .= "Upgrade: websocketrn";
$headers .= "Connection: Upgradern";
$headers .= "Sec-WebSocket-Version: 13rn";
$headers .= "Sec-WebSocket-Accept: $keyrnrn";
socket_write($client, $headers, strlen($headers));
<?php
$dataFileName = 'data.txt';
while(true)
{
$requestedTimestamp = $_GET['timestamp']
$modifiedAt = filemtime( $dataFileName );
if ( $modifiedAt > $requestedTimestamp )
{
$data = file_get_contents($dataFileName);
sleep(1);
$content = 'Content: '.$data;
$response = chr(129) . chr(strlen($content)) . $content;
socket_write($client, $response);
}
}
<html>
<body>
<div id="root"></div>
<script>
var host = 'ws://0.0.0.0:3031/websockets.php';
var socket = new WebSocket(host);
socket.onmessage = function(e) {
document.getElementById('root').innerHTML = e.data;
};
</script>
</body>
</html>
Bibliotecas
Frameworks
A simplicidade das interfaces
<?php
public function onOpen(ConnectionInterface $conn) {
}
public function onMessage(ConnectionInterface $from, $msg) {
}
public function onClose(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, Exception $e) {
}
$app = new RatchetApp('localhost', 8080);
<?php
$ws_worker = new Worker("websocket://0.0.0.0:2348");
$ws_worker->onConnect = function($connection)
{
};
$ws_worker->onMessage = function($connection, $data)
{
$connection->send('hello ' . $data);
};
$ws_worker->onClose = function($connection)
{
};
var host = 'ws://0.0.0.0:3030/websockets.php';
var socket = new WebSocket(host);
socket.onopen = function(e) {
socket.send("Texto que pode enviado pro servidor!");
};
socket.onmessage = function(e) {
};
socket.close();
COMPATIBILIDADE
REFERÊNCIAS
https://pt.wikipedia.org/wiki/Tempo_rea
l
https://tools.ietf.org/html/rfc6202
https://repositorio.ufsc.br/bitstream/ha
ndle/123456789/184634/desenvolviment
o-de-aplicacoes-com-websockets.pdf?
sequence=-1
https://developer.mozilla.org/en-US/doc
s/Web/API/WebSockets_API/Writing_W
ebSocket_client_applications
https://www.php.net/manual/pt_BR/soc
kets.examples.php
https://www.php.net/manual/pt_BR/soc
kets.examples.php
https://tools.ietf.org/html/rfc6455
https://phppot.com/php/simple-php-cha
t-using-websocket/
https://developer.mozilla.org/en-US/doc
s/Web/API/WebSockets_API
http://www.workerman.net/en/
http://socketo.me/
https://symfony.com/doc/current/comp
onents/mercure.html
OBRIGADO A TODOS!
EDUARDO CESAR
github.com/bolinha1
/in/eduardo-cesar-oliveira
slideshare.net/EduardoCesar10
eduardo.oliveira@zarpsystem.com.br
www.zarpsystem.com.br
https://joind.in/talk/67610
ESTAMOS CONTRATANDO!!!

Desenvolvendor aplicações real time com PHP