Niklas Büsing Niklas Büsing - 2 months ago 15
Linux Question

Socket send data entered in Terminal

I want to create a Socket that listens to connections and sends data which i enter in terminal (want to run it using php script.php) to all Clients

any direction too look?

best regards,
Jack

Answer

This script does what you want and also writes data sent by the clients to your terminal, run using php script.php:

<?php

$port = 12345;
$server = stream_socket_server("tcp://localhost:$port", $errno, $errstr);
if (!$server) die("$errstr (errno $errno)\n");

$s = array(STDIN, $server); // initially wait for terminal input or connections
while ($r = $s and stream_select($r, $n=NULL, $n=NULL, NULL))
foreach ($r as $stream)
    if ($stream == STDIN)   // terminal input
    {
        $data = fgets(STDIN);
        foreach (array_slice($s, 2) as $client)     // clients from index 2 on
            fputs($client, $data);
    }
    else
    if ($stream == $server) // new client
        $s[] = stream_socket_accept($server, -1);   // add it to $s (index 2 on)
    else                    // data from a client
        if (!fputs(STDOUT, fgets($stream)))
        {
            fclose($stream);
            array_splice($s, array_search($stream, $s), 1); // remove client
        }

?>