fork download
  1. <?php
  2.  
  3. if ( !$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) ) {
  4. throw new Exception('socket_create failed: ' . socket_strerror(socket_last_error()) );
  5. }
  6. if (!$sb = socket_bind($server, '0.0.0.0', 8081) ) {
  7. throw new Exception('socket_bind failed: ' . socket_strerror(socket_last_error()) );
  8. }
  9. if (!$sl = socket_listen($server, 128)) {
  10. throw new Exception('socket_listen failed: ' . socket_strerror(socket_last_error()));
  11. }
  12.  
  13. $read = array($server);
  14. $write = $except = $clients = $readBuffer = $writeBuffer = array();
  15.  
  16. while (true) {
  17. socket_select($read, $write, $except, null);
  18. if (in_array($server, $read)) {
  19. if ( ($conn = socket_accept($server)) < 0 ) {
  20. throw new Exception('socket_accept() failed: '
  21. }
  22. $clients[intval($conn)] = $conn;
  23. $readBuffer[intval($conn)] = "";
  24. $writeBuffer[intval($conn)] = 0;
  25. }
  26. foreach ($read as $r) {
  27. if ($r == $server) continue;
  28. if (false === ($data = socket_read($r, 1024)) ) {
  29. /*throw new Exception( 'socket_read failed: '
  30.   . socket_strerror(socket_last_error()) );*/
  31. /* То ли клиент отсоединился, то ли ошибка */
  32. $readBuffer[intval($r)],
  33. $writeBuffer[intval($r)],
  34. $clients[intval($r)]
  35. );
  36. } elseif (feof($r)) {
  37. foreach ($clients as $client) {
  38. if ($client === $r) continue;
  39. $written = socket_write($client, "user " . intval($r) . ": "
  40. . substr($readBuffer[intval($r)], $writeBuffer[intval($client)]) );
  41. $writeBuffer[intval($client)] += $written;
  42. }
  43. } else {
  44. $readBuffer[intval($r)] .= $data;
  45. }
  46. }
  47. $read = $clients;
  48. $write = $clients;
  49. $read[] = $server;
  50. }
Time limit exceeded #stdin #stdout 5s 61632KB
stdin
Standard input is empty
stdout
Standard output is empty