Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- error_reporting(E_ALL);
- /* Allow the script to hang around waiting for connections. */
- set_time_limit(0);
- /* Turn on implicit output flushing so we see what we're getting
- * as it comes in. */
- ob_implicit_flush();
- $address = 'xx';
- $port = 1;
- if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
- echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
- }
- if (socket_bind($sock, $address, $port) === false) {
- echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
- }
- if (socket_listen($sock, 5) === false) {
- echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
- }
- $clients = array();
- $read = array();
- $write = NULL;
- $except = NULL;
- $foo = true;
- $msg = "";
- do {
- $read[0] = $sock;
- //For each active client
- for($i = 0; $i < count($clients); $i++)
- {
- if($clients[$i] != null) unset($clients[$i]);
- else
- $read[$i+1] = $clients;
- }
- //Check for new clients
- $num_changed_sockets = socket_select($read, $write, $except, 0, 1);
- // Determine if we already have this client
- if(!in_array($sock,$read))
- {
- if (($msgsock = socket_accept($sock)) === false) {
- echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
- }
- else
- {
- $clients[] = $msgsock;
- $caddress = "";
- $cport = "";
- $client_count = "Client count: ".count($clients);
- socket_getpeername($msgsock,&$caddress,&$cport);
- /* Send instructions. */
- $msg .= "\nTCP server connection established \n".$client_count."\n";
- $msg .= "Client connected ".$caddress." {##}\n";
- socket_write($msgsock, $msg, strlen($msg));
- echo $msg;
- }
- }
- print_r($clients);
- //For each active client
- for($i = 0; $i < count($clients); $i++)
- {
- var_dump($clients[$i]);
- echo "blocking";
- if (false === ($input = socket_read($clients[$i], 2048, PHP_BINARY_READ))) {
- echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
- }
- echo "\ninput says\n";
- echo var_dump($input);
- if(empty($input)) continue;
- // Shutdown the server
- if($input=="shutdown")
- {
- echo "Shutting down..";
- socket_close($clients[$i]);
- }
- //Write reponse back to all the clients
- for($j = 0; $j < count($clients); $j++)
- {
- // socket_write($clients[$j],$input,strlen($input));
- }
- }
- } while ($foo);
- socket_close($sock);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement