dqkf36241 2016-06-27 13:11
浏览 19
已采纳

套接字发送在终端中输入的数据

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

  • 写回答

2条回答 默认 最新

  • dongzhao8233 2016-07-19 09:18
    关注

    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)
    ");
    
    $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
            }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导