22
33require __DIR__ .'/vendor/autoload.php ' ;
44
5+ // Include Ratchet
56use Ratchet \Server \IoServer ;
67use Ratchet \Http \HttpServer ;
78use Ratchet \WebSocket \WsServer ;
89use Ratchet \MessageComponentInterface ;
910use Ratchet \ConnectionInterface ;
1011
12+ // Define the app port
1113define ('APP_PORT ' , 8080 );
1214
1315class ServerImpl implements MessageComponentInterface {
@@ -17,39 +19,52 @@ public function __construct() {
1719 $ this ->clients = new \SplObjectStorage ;
1820 }
1921
22+ /**
23+ * A new connection is on
24+ * @param ConnectionInterface $conn Connection data
25+ */
2026 public function onOpen (ConnectionInterface $ conn ) {
2127 $ this ->clients ->attach ($ conn );
22- echo "New connection! ( {$ conn ->resourceId }). \n" ;
28+ echo "New connection : {$ conn ->resourceId }\n" ;
2329 }
2430
31+ /**
32+ * A message is received
33+ * @param ConnectionInterface $conn Sender connection data
34+ * @param String $msg The received message
35+ */
2536 public function onMessage (ConnectionInterface $ conn , $ msg ) {
26- echo sprintf ("New message from '%s': %s \n\n\n" , $ conn ->resourceId , $ msg );
27- foreach ($ this ->clients as $ client ) { // BROADCAST
37+ echo sprintf ("New message from '%s': %s \n" , $ conn ->resourceId , $ msg );
38+ // Send the received message to all connected clients
39+ foreach ($ this ->clients as $ client ) {
2840 $ message = json_decode ($ msg , true );
2941 if ($ conn !== $ client ) {
3042 $ client ->send ($ msg );
3143 }
3244 }
3345 }
3446
47+ /**
48+ * A connection is over
49+ * @param ConnectionInterface $conn Connection data
50+ */
3551 public function onClose (ConnectionInterface $ conn ) {
3652 $ this ->clients ->detach ($ conn );
37- echo "Connection {$ conn ->resourceId } is gone . \n" ;
53+ echo "Connection to {$ conn ->resourceId } is over . \n" ;
3854 }
3955
56+ /**
57+ * An error is occured
58+ * @param ConnectionInterface $conn Involved connection data
59+ * @param Exception $e Error data
60+ */
4061 public function onError (ConnectionInterface $ conn , \Exception $ e ) {
41- echo "An error occured on connection {$ conn ->resourceId }: {$ e ->getMessage ()}\n\n\n " ;
62+ echo "An error occured on connection {$ conn ->resourceId }: {$ e ->getMessage ()}\n\n" ;
4263 $ conn ->close ();
4364 }
4465}
4566
46- $ server = IoServer::factory (
47- new HttpServer (
48- new WsServer (
49- new ServerImpl ()
50- )
51- ),
52- APP_PORT
53- );
54- echo "Server created on port " . APP_PORT . "\n\n" ;
67+ // Create and run the server
68+ $ server = IoServer::factory (new HttpServer (new WsServer (new ServerImpl ())), APP_PORT );
69+ echo "Server is running on port " . APP_PORT . "... \n" ;
5570$ server ->run ();
0 commit comments