OpenSwoole\Event::write

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Event::write(mixed $fd, mixed $data)\:\ bool

Parameters

fd

fd of the socket type

data

Data to send to the socket, must not exceed the length of the transmission data buffer size

Return

success

If success, it returns TRUE, meaning the event listener was successfully added

Otherwise it returns FALSE, meaning there was an issue registering the event

Description

Write data to the socket with async I/O, by using Event::write you can achieve asynchronous data transmission, once the data buffer is full, a EAGAIN error will be returned and the data waiting for a read event will be added to the transmission queue, once the socket is writeable again, OpenSwoole will automatically listen for the write event again.

When using Event:write, if the operation is successful, the event loop automatically switches the socket to non-blocking mode. You also should not use Event::write with SSL/TLS connections.

Under the hood, OpenSwoole will allow you to write as long as the buffer is not full, if it is full, OpenSwoole will write the extra data to memory and save it until a writeable event is triggered and the buffer becomes free again. If the memory buffer is also filled, OpenSwoole will then throw a pipe buffer overflow error and block the event loop waiting to write again.

Example

<?php

$fp = stream_socket_client('tcp://127.0.0.1:9501');
$data = str_repeat('A', 1024 * 1024 * 2);

// Create the read callback
OpenSwoole\Event::add($fp, function($fp) {
     echo fread($fp);
});

// Write data to the socket
OpenSwoole\Event::write($fp, $data);
Last updated on September 1, 2022