1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
<?php
ob_start();
header("HTTP/1.1 200 OK");
header("Content-length: " . (string)ob_get_length());
ob_end_flush();
$data = json_decode(file_get_contents("php://input"), true);
require '../../tools/ratchet/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
define('SOCKET_PORT',9095);
class SocketServer implements MessageComponentInterface{
protected $clients;
private $subscriptions;
private $users;
protected $getData;
public function __construct(){
$this->clients = new SplObjectStorage;
$this->subscriptions = [];
$this->users = [];
global $data;
$this->getData =& $data;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
$this->user[$conn->resourceId] = $conn;
echo "New connection! ({$conn->resourceId}).\n";
}
public function onMessage(ConnectionInterface $conn, $msg) {
$msg = json_decode($msg);
switch($msg->command){
case "subscribe":
$this->subscriptions[$conn->resourceId] = $msg->message->id_user;
echo sprintf("user id '%d' : \n\n\n",$this->subscriptions[$conn->resourceId]);
break;
default:
break;
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
unset($this->users[$conn->resourceId]);
unset($this->subscriptions[$conn->resourceId]);
echo "Connection {$conn->resourceId} is gone.\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error occured on connection {$conn->resourceId}: {$e->getMessage()}\n\n\n";
$conn->close();
}
}
$server = IoServer::factory(new HttpServer(new WsServer(new SocketServer())),SOCKET_PORT);
echo "Server created...... " ."\n\n";
echo "Server created on port " . SOCKET_PORT ."\n\n";
$server->run();
?> |
Partager