@@ -22,43 +22,45 @@ function startChatServer(string $host, int $port): void
2222 $ clients [$ id ] = $ client ;
2323
2424 // Handle each client in a separate coroutine and child scope
25- spawn with Scope::inherit() use ($ client , $ id , &$ clients ) {
26- try {
27- // Send welcome message
28- socket_write ($ client , "Welcome to the chat room! \n" );
29-
30- // Read messages from this client and broadcast them
31- while (true ) {
32- $ message = socket_read ($ client , 1024 );
33-
34- if ($ message === false || $ message === '' ) {
35- break ; // Client disconnected
36- }
37-
38- $ broadcastMsg = "Client $ id: $ message " ;
39- echo $ broadcastMsg ;
25+ spawn use($ client , $ id , &$ clients) {
26+ async inherited $ clientScope {
27+ try {
28+ // Send welcome message
29+ socket_write ($ client , "Welcome to the chat room! \n" );
4030
41- // Broadcast to all other clients
42- foreach ($ clients as $ cid => $ c ) {
43- if ($ cid !== $ id ) {
44- spawn socket_write ($ c , $ broadcastMsg );
31+ // Read messages from this client and broadcast them
32+ while (true ) {
33+ $ message = socket_read ($ client , 1024 );
34+
35+ if ($ message === false || $ message === '' ) {
36+ break ; // Client disconnected
37+ }
38+
39+ $ broadcastMsg = "Client $ id: $ message " ;
40+ echo $ broadcastMsg ;
41+
42+ // Broadcast to all other clients
43+ foreach ($ clients as $ cid => $ c ) {
44+ if ($ cid !== $ id ) {
45+ spawn socket_write ($ c , $ broadcastMsg );
46+ }
4547 }
4648 }
47- }
48- } catch (Exception $ e ) {
49- echo "Error handling client $ id: " . $ e ->getMessage () . "\n" ;
50- } finally {
51- // Gracefully handle connection cancellation
52- try {
53- await $ clientScope ->allTask () until Async \timeout (2000 );
49+ } catch (Exception $ e ) {
50+ echo "Error handling client $ id: " . $ e ->getMessage () . "\n" ;
5451 } finally {
55- // Clean up when client disconnects
56- socket_close ($ client );
57- unset($ clients [$ id ]);
58- echo "Client $ id disconnected \n" ;
52+ // Gracefully handle connection cancellation
53+ try {
54+ await $ clientScope ->allTask () until Async \timeout (2000 );
55+ } finally {
56+ // Clean up when client disconnects
57+ socket_close ($ client );
58+ unset($ clients [$ id ]);
59+ echo "Client $ id disconnected \n" ;
60+ }
5961 }
60- }
61- };
62+ };
63+ }
6264 }
6365 };
6466
0 commit comments