0

I have been trying PHP Sockets lately. I could use some help understanding a few things.

Once I start a socket and begin listening:

socket_server.php:

socket_create(AF_INET, SOCK_STREAM, 0); 
socket_bind($socket, $host, $port); 
socket_listen($socket, 3);

How do I then :

  • shut down the socket on that port whenever I want to?

So the socket is running via initiating 'socket_server.php' and I decide I would like to shut it down. If I have not added any 'socket_close()' to 'socket_server.php' how do I shut it down?

  • keep track of if the socket listener is still running?

Once I have initiated 'socket_server.php' - how do I monitor that it is still running?

Thank you.

TV-C-1-5
  • 680
  • 2
  • 13
  • 19
  • 2
    If the PHP script isn't running then it isn't listening on that port. Not bad practice to write some code to try shutdown and close the connection on exit though. You are maybe talking about "daemonizing" a PHP script. I love PHP but work with something like nodeJS for a bit and it will be hard to write server side socket stuff in PHP. [Run php script as daemon process](https://stackoverflow.com/questions/2036654/run-php-script-as-daemon-process) – ficuscr Feb 23 '22 at 01:08
  • Not sure I follow. Perhaps that is why I am here. I assumed that I start the PHP listener script in terminal and it runs indefinitely when setting 'set_time_limit(0)'. As per here: https://www.php.net/manual/en/sockets.examples.php That is why I was trying to figure out how to shut it down. – TV-C-1-5 Feb 23 '22 at 01:17
  • 2
    Think the link in my first comment covers that. `foreground` `background`. The daemon process means you could have it managed by systemd and start up like say httpd or php-fpm processes. eg. What if the server restarts? – ficuscr Feb 23 '22 at 01:32
  • Anyway, `socket_listen()` is not a blocking call, it will return immediately and without more php code the script will exit. You need `socket_accept()` after that if you want to handle incoming connections. – President James K. Polk Feb 23 '22 at 12:41

0 Answers0