|
| 1 | +<?php |
| 2 | + |
| 3 | +$host = '0.0.0.0'; |
| 4 | +$port = 1234; |
| 5 | +$outputFile = __DIR__ . '/received_data.txt'; |
| 6 | + |
| 7 | +$serverSocket = stream_socket_server("tcp://$host:$port", $errno, $errstr); |
| 8 | +if (!$serverSocket) { |
| 9 | + die("Error: $errstr ($errno)\n"); |
| 10 | +} |
| 11 | +stream_set_blocking($serverSocket, false); // Non-blocking server socket |
| 12 | + |
| 13 | +$clients = []; |
| 14 | + |
| 15 | +echo "Server listening on $host:$port...\n"; |
| 16 | + |
| 17 | +while (true) { |
| 18 | + $readSockets = [$serverSocket]; |
| 19 | + $readSockets = array_merge($readSockets, $clients); |
| 20 | + |
| 21 | + $write = $except = null; |
| 22 | + // Wait for activity on any socket |
| 23 | + if (stream_select($readSockets, $write, $except, 0, 200000)) { |
| 24 | + foreach ($readSockets as $socket) { |
| 25 | + if ($socket === $serverSocket) { |
| 26 | + // Accept new connection |
| 27 | + $newClient = stream_socket_accept($serverSocket, 0); |
| 28 | + if ($newClient) { |
| 29 | + stream_set_blocking($newClient, false); // Non-blocking client |
| 30 | + $clients[] = $newClient; |
| 31 | + echo "New connection accepted\n"; |
| 32 | + } |
| 33 | + } else { |
| 34 | + // Read from an existing client |
| 35 | + $data = fread($socket, 1024); |
| 36 | + if ($data === '' || $data === false) { |
| 37 | + echo "Client disconnected\n"; |
| 38 | + fclose($socket); |
| 39 | + $clients = array_filter($clients, fn($c) => $c !== $socket); |
| 40 | + } else { |
| 41 | + file_put_contents($outputFile, $data, FILE_APPEND); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // Small delay to prevent high CPU usage |
| 48 | + usleep(10000); |
| 49 | +} |
0 commit comments