@@ -10,7 +10,7 @@ if (!extension_loaded('sockets')) {
1010<?php
1111
1212use function Async \spawn ;
13- use function Async \awaitAll ;
13+ use function Async \awaitAllOrFail ;
1414use function Async \delay ;
1515
1616echo "Start \n" ;
@@ -27,56 +27,61 @@ $server = spawn(function() use (&$port, &$output) {
2727 socket_set_option ($ socket , SOL_SOCKET , SO_REUSEADDR , 1 );
2828 socket_bind ($ socket , '127.0.0.1 ' , 0 );
2929 socket_listen ($ socket , 5 );
30-
30+
3131 $ addr = '' ;
3232 socket_getsockname ($ socket , $ addr , $ port );
3333 $ output [] = "Server: listening on port $ port " ;
34-
34+
3535 $ clients = [];
36-
36+
3737 // Accept 3 clients
3838 for ($ i = 1 ; $ i <= 3 ; $ i ++) {
3939 $ output [] = "Server: waiting for client $ i " ;
4040 $ client = socket_accept ($ socket );
4141 $ output [] = "Server: client $ i connected " ;
4242 $ clients [] = $ client ;
4343 }
44-
44+
4545 // Send responses to all clients
4646 foreach ($ clients as $ i => $ client ) {
4747 $ clientNum = $ i + 1 ;
4848 socket_write ($ client , "Response to client $ clientNum " );
4949 socket_close ($ client );
5050 }
51-
51+
5252 socket_close ($ socket );
5353});
5454
5555// Multiple client coroutines
5656$ clients = [];
5757for ($ i = 1 ; $ i <= 3 ; $ i ++) {
5858 $ clients [] = spawn (function () use (&$ port , $ i , &$ output ) {
59- while ($ port === null ) {
60- delay (1 );
59+
60+ for ($ i = 0 ; $ i < 3 && $ port === null ; $ i ++) {
61+ delay (10 );
6162 }
62-
63+
64+ if (empty ($ port )) {
65+ throw new Exception ("Server port is not provided... " );
66+ }
67+
6368 // Small delay to stagger connections
6469 delay ($ i );
65-
70+
6671 $ output [] = "Client $ i: connecting " ;
6772 $ socket = socket_create (AF_INET , SOCK_STREAM , SOL_TCP );
68-
73+
6974 if (socket_connect ($ socket , '127.0.0.1 ' , $ port )) {
7075 $ output [] = "Client $ i: connected " ;
7176 $ data = socket_read ($ socket , 1024 );
7277 $ output [] = "Client $ i: received ' $ data' " ;
7378 }
74-
79+
7580 socket_close ($ socket );
7681 });
7782}
7883
79- awaitAll (array_merge ([$ server ], $ clients ));
84+ awaitAllOrFail (array_merge ([$ server ], $ clients ));
8085
8186// Sort and output results
8287sort ($ output );
@@ -106,4 +111,4 @@ Server: listening on port %d
106111Server: waiting for client 1
107112Server: waiting for client 2
108113Server: waiting for client 3
109- End
114+ End
0 commit comments