请教下关于swoole_event_add中可写回调什么时候触发

// client
<?php
$socket = stream_socket_client('tcp://127.0.0.1:9502', $errno, $errstr, 30);

function onRead()
{
    global $socket;
    $buffer = stream_socket_recvfrom($socket, 1024);
    if (empty($buffer)) {
        echo 'server closed' . PHP_EOL;
        swoole_event_del($socket);
    }
    // echo $buffer;
    echo 'Recv:' . $buffer . PHP_EOL;
    fwrite(STDOUT, 'Enter Msg:');
}

function onWrite()
{
    global $socket;
    echo 'on write' . PHP_EOL;
}

function onInput()
{
    global $socket;
    $msg = trim(fgets(STDIN));
    if ($msg === 'exit') {
        swoole_event_exit();
        exit();
    }
    swoole_event_write($socket, $msg);
    fwrite(STDOUT, 'Enter Msg:' . PHP_EOL);
}

swoole_event_add($socket, 'onRead', 'onWrite');
swoole_event_add(STDIN, 'onInput');

fwrite(STDOUT, 'Enter Msg:');
// server
<?php

class Server
{
    /**
     * @var swoole_server
     */
    private $server;

    /**
     * Server constructor.
     */
    public function __construct()
    {
        $this->boot();
    }

    private function boot()
    {
        $this->server = new swoole_server('0.0.0.0', 9502);

        $this->server->set(['worker_num' => 1]);

        $this->server->on('start', [$this, 'onStart']);

        $this->server->on('connect', [$this, 'onConnect']);

        $this->server->on('receive', [$this, 'onReceive']);

        $this->server->on('close', [$this, 'onClose']);
        $this->server->start();
    }

    public function onStart(swoole_server $server)
    {
        echo 'start' . PHP_EOL;
    }

    public function onConnect(swoole_server $server,$fd,$fromId)
    {
        echo 'client ' . $fd .' connect' . PHP_EOL;
    }

    public function onClose(swoole_server $server,$fd,$fromId)
    {
        echo 'client ' . $fd .' close connection' . PHP_EOL;
    }

    public function onReceive(swoole_server $server,$fd,$fromId,$data)
    {
        echo 'get msg from client ' . $fd . ' ,data:' . $data . PHP_EOL;
        foreach ($this->server->connections as $connection) {
            // if($fd == $connection) {
            //     continue;
            // }
            $server->send($connection,$data);
        }
    }
}

new Server();

问题描述:我尝试触发可写回调onWrite,试了很多次不能成功触发,暂时没找到原因,还请指教

2018-03-31 20:43
0

要回复问题请先登录注册