• Process\Pool->write
    • 实例
    • 调用端

    Process\Pool->write

    向对端写入数据,必须在$ipc_modeSWOOLE_IPC_SOCKET时才能使用。

    1. function Process\Pool::write(string $data);
    • $data:写入的数据内容。可多次调用write,底层会在onMessage函数退出后将数据全部写入socket中,并close连接
    • 此方法为内存操作,没有IO消耗
    • 发送数据操作是同步阻塞IO

    实例

    1. $pool = new Swoole\Process\Pool(2, SWOOLE_IPC_SOCKET);
    2. $pool->on("Message", function ($pool, $message) {
    3. echo "Message: {$message}\n";
    4. $pool->write("hello ");
    5. $pool->write("world ");
    6. $pool->write("\n");
    7. });
    8. $pool->listen('127.0.0.1', 8089);
    9. $pool->start();

    调用端

    1. $fp = stream_socket_client("tcp://127.0.0.1:8089", $errno, $errstr) or die("error: $errstr\n");
    2. $msg = json_encode(['data' => 'hello', 'uid' => 1991]);
    3. fwrite($fp, pack('N', strlen($msg)) . $msg);
    4. sleep(1);
    5. //将显示 hello world\n
    6. var_dump(fread($fp, 8192));
    7. fclose($fp);