PHP Socket Server


SUBMITTED BY: chrischenai

DATE: Oct. 18, 2017, 7:38 p.m.

FORMAT: PHP

SIZE: 1.9 kB

HITS: 484

  1. #!/usr/local/bin/php -q
  2. <?php
  3. error_reporting(E_ALL);
  4. /* Allow the script to hang around waiting for connections. */
  5. set_time_limit(0);
  6. /* Turn on implicit output flushing so we see what we're getting
  7. * as it comes in. */
  8. ob_implicit_flush();
  9. $address = '192.168.1.53';
  10. $port = 10000;
  11. if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
  12. echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
  13. }
  14. if (socket_bind($sock, $address, $port) === false) {
  15. echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
  16. }
  17. if (socket_listen($sock, 5) === false) {
  18. echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
  19. }
  20. do {
  21. if (($msgsock = socket_accept($sock)) === false) {
  22. echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
  23. break;
  24. }
  25. /* Send instructions. */
  26. $msg = "\nWelcome to the PHP Test Server. \n" .
  27. "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
  28. socket_write($msgsock, $msg, strlen($msg));
  29. do {
  30. if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
  31. echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
  32. break 2;
  33. }
  34. if (!$buf = trim($buf)) {
  35. continue;
  36. }
  37. if ($buf == 'quit') {
  38. break;
  39. }
  40. if ($buf == 'shutdown') {
  41. socket_close($msgsock);
  42. break 2;
  43. }
  44. $talkback = "PHP: You said '$buf'.\n";
  45. socket_write($msgsock, $talkback, strlen($talkback));
  46. echo "$buf\n";
  47. } while (true);
  48. socket_close($msgsock);
  49. } while (true);
  50. socket_close($sock);
  51. ?>

comments powered by Disqus