PHP Echo-Server
Ein einfacher TCP-Echo-Server implementiert als PHP-Standalone (CLI) Anwendung.
PHP Sockets - (socket.php)
- #!/usr/bin/php
- <?php
- declare(ticks=1); // obsolete in php 5.3.0 and above
- function do_terminate()
- {
- $run_loop = false;
- }
- function signal_handler($signo)
- {
- switch ($signo) {
- case SIGALRM:
- case SIGQUIT:
- case SIGINT:
- case SIGKILL:
- case SIGTERM:
- case SIGHUP:
- case SIGUSR1:
- case SIGUSR2:
- do_terminate();
- break;
- default:
- }
- }
- $run_loop = true;
- // catch signals to terminate the process manually and close the sockets
- pcntl_signal(SIGQUIT, 'signal_handler');
- pcntl_signal(SIGTERM, 'signal_handler');
- pcntl_signal(SIGINT, 'signal_handler');
- pcntl_signal(SIGHUP, 'signal_handler');
- pcntl_signal(SIGUSR1, 'signal_handler');
- pcntl_signal(SIGUSR2, 'signal_handler');
- // the script is allowed to run unlimited (FIXME: is this really needed in CLI mode? i think not)
- // Set the ip and port we will listen on
- $address = 'localhost';
- $port = 22222;
- // create a tcp stream socket
- if ($socket === false)
- {
- }
- // set socket option, to reuse the socket, even if the adress is already in use
- // this is needed, if the socket was not properly shutdown (from server or from client)
- // bind the socket to address & port
- {
- }
- // Listen for new connections
- {
- }
- // loop until a signal sets run_loop
- while ($run_loop) {
- // copy the clients array
- $read = $socket_clients;
- // recieve a list of clients, that has data to read
- if ($result === false)
- {
- }
- else if ($result > 0)
- {
- // check for new connections
- $socket_clients[] = $socket_new;
- // unset the socket from read array
- }
- // now loop through the other sockets in the read array, and read the data
- foreach ($read as $socket_read) {
- // read data
- $buffer_read = socket_read($socket_read, 4096, PHP_BINARY_READ); //in PHP_NORMAL_READ, you should use @socket_read, to supress the error, if a client disconnect
- // has client socket be closed? (works in PHP_NORMAL_READ)
- if ($buffer_read === false) {
- }
- else // socket not closed, data to read
- {
- // broadcast the message, to all other clients
- foreach ($socket_clients as $socket_write)
- {
- if (($socket_write != $socket) && ($socket_write != $socket_read))
- {
- }
- }
- }
- else // has client socket be closed? (works in PHP_BINARY_READ)
- {
- }
- }
- }
- }
- }
- // close the Server
- ?>