Documentation

ConnectionInterface extends DuplexStreamInterface

Any incoming and outgoing connection is represented by this interface, such as a normal TCP/IP connection.

An incoming or outgoing connection is a duplex stream (both readable and writable) that implements React's DuplexStreamInterface. It contains additional properties for the local and remote address (client IP) where this connection has been established to/from.

Most commonly, instances implementing this ConnectionInterface are emitted by all classes implementing the ServerInterface and used by all classes implementing the ConnectorInterface.

Because the ConnectionInterface implements the underlying DuplexStreamInterface you can use any of its events and methods as usual:

$connection->on('data', function ($chunk) {
    echo $chunk;
});

$connection->on('end', function () {
    echo 'ended';
});

$connection->on('error', function (Exception $e) {
    echo 'error: ' . $e->getMessage();
});

$connection->on('close', function () {
    echo 'closed';
});

$connection->write($data);
$connection->end($data = null);
$connection->close();
// …

For more details, see the DuplexStreamInterface.

Tags
see
DuplexStreamInterface
see
ServerInterface
see
ConnectorInterface

Table of Contents

Methods

close()  : void
Closes the stream (forcefully).
emit()  : mixed
end()  : void
Successfully ends the stream (after optionally sending some final data).
getLocalAddress()  : string|null
Returns the full local address (full URI with scheme, IP and port) where this connection has been established with
getRemoteAddress()  : string|null
Returns the full remote address (URI) where this connection has been established with
isReadable()  : bool
Checks whether this stream is in a readable state (not closed already).
isWritable()  : bool
Checks whether this stream is in a writable state (not closed already).
listeners()  : mixed
on()  : mixed
once()  : mixed
pause()  : void
Pauses reading incoming data events.
pipe()  : WritableStreamInterface
Pipes all the data from this readable source into the given writable destination.
removeAllListeners()  : mixed
removeListener()  : mixed
resume()  : void
Resumes reading incoming data events.
write()  : bool
Write some data into the stream.

Methods

close()

Closes the stream (forcefully).

public close() : void

This method can be used to (forcefully) close the stream.

$stream->close();

Once the stream is closed, it SHOULD emit a close event. Note that this event SHOULD NOT be emitted more than once, in particular if this method is called multiple times.

After calling this method, the stream MUST switch into a non-readable mode, see also isReadable(). This means that no further data or end events SHOULD be emitted.

$stream->close();
assert($stream->isReadable() === false);

$stream->on('data', assertNeverCalled());
$stream->on('end', assertNeverCalled());

If this stream is a DuplexStreamInterface, you should also notice how the writable side of the stream also implements a close() method. In other words, after calling this method, the stream MUST switch into non-writable AND non-readable mode, see also isWritable(). Note that this method should not be confused with the end() method.

Tags
see
WritableStreamInterface::close()

emit()

public emit(mixed $event[, array<string|int, mixed> $arguments = [] ]) : mixed
Parameters
$event : mixed
$arguments : array<string|int, mixed> = []

end()

Successfully ends the stream (after optionally sending some final data).

public end([mixed|string|null $data = null ]) : void

This method can be used to successfully end the stream, i.e. close the stream after sending out all data that is currently buffered.

$stream->write('hello');
$stream->write('world');
$stream->end();

If there's no data currently buffered and nothing to be flushed, then this method MAY close() the stream immediately.

If there's still data in the buffer that needs to be flushed first, then this method SHOULD try to write out this data and only then close() the stream. Once the stream is closed, it SHOULD emit a close event.

Note that this interface gives you no control over explicitly flushing the buffered data, as finding the appropriate time for this is beyond the scope of this interface and left up to the implementation of this interface.

Many common streams (such as a TCP/IP connection or file-based stream) may choose to buffer all given data and schedule a future flush by using an underlying EventLoop to check when the resource is actually writable.

You can optionally pass some final data that is written to the stream before ending the stream. If a non-null value is given as $data, then this method will behave just like calling write($data) before ending with no data.

// shorter version
$stream->end('bye');

// same as longer version
$stream->write('bye');
$stream->end();

After calling this method, the stream MUST switch into a non-writable mode, see also isWritable(). This means that no further writes are possible, so any additional write() or end() calls have no effect.

$stream->end();
assert($stream->isWritable() === false);

$stream->write('nope'); // NO-OP
$stream->end(); // NO-OP

If this stream is a DuplexStreamInterface, calling this method SHOULD also end its readable side, unless the stream supports half-open mode. In other words, after calling this method, these streams SHOULD switch into non-writable AND non-readable mode, see also isReadable(). This implies that in this case, the stream SHOULD NOT emit any data or end events anymore. Streams MAY choose to use the pause() method logic for this, but special care may have to be taken to ensure a following call to the resume() method SHOULD NOT continue emitting readable events.

Note that this method should not be confused with the close() method.

Parameters
$data : mixed|string|null = null

getLocalAddress()

Returns the full local address (full URI with scheme, IP and port) where this connection has been established with

public getLocalAddress() : string|null
$address = $connection->getLocalAddress();
echo 'Connection with ' . $address . PHP_EOL;

If the local address can not be determined or is unknown at this time (such as after the connection has been closed), it MAY return a NULL value instead.

Otherwise, it will return the full address (URI) as a string value, such as tcp://127.0.0.1:8080, tcp://[::1]:80, tls://127.0.0.1:443, unix://example.sock or unix:///path/to/example.sock. Note that individual URI components are application specific and depend on the underlying transport protocol.

This method complements the getRemoteAddress() method, so they should not be confused.

If your TcpServer instance is listening on multiple interfaces (e.g. using the address 0.0.0.0), you can use this method to find out which interface actually accepted this connection (such as a public or local interface).

If your system has multiple interfaces (e.g. a WAN and a LAN interface), you can use this method to find out which interface was actually used for this connection.

Tags
see
self::getRemoteAddress()
Return values
string|null

local address (URI) or null if unknown

getRemoteAddress()

Returns the full remote address (URI) where this connection has been established with

public getRemoteAddress() : string|null
$address = $connection->getRemoteAddress();
echo 'Connection with ' . $address . PHP_EOL;

If the remote address can not be determined or is unknown at this time (such as after the connection has been closed), it MAY return a NULL value instead.

Otherwise, it will return the full address (URI) as a string value, such as tcp://127.0.0.1:8080, tcp://[::1]:80, tls://127.0.0.1:443, unix://example.sock or unix:///path/to/example.sock. Note that individual URI components are application specific and depend on the underlying transport protocol.

If this is a TCP/IP based connection and you only want the remote IP, you may use something like this:

$address = $connection->getRemoteAddress();
$ip = trim(parse_url($address, PHP_URL_HOST), '[]');
echo 'Connection with ' . $ip . PHP_EOL;
Return values
string|null

remote address (URI) or null if unknown

isReadable()

Checks whether this stream is in a readable state (not closed already).

public isReadable() : bool

This method can be used to check if the stream still accepts incoming data events or if it is ended or closed already. Once the stream is non-readable, no further data or end events SHOULD be emitted.

assert($stream->isReadable() === false);

$stream->on('data', assertNeverCalled());
$stream->on('end', assertNeverCalled());

A successfully opened stream always MUST start in readable mode.

Once the stream ends or closes, it MUST switch to non-readable mode. This can happen any time, explicitly through close() or implicitly due to a remote close or an unrecoverable transmission error. Once a stream has switched to non-readable mode, it MUST NOT transition back to readable mode.

If this stream is a DuplexStreamInterface, you should also notice how the writable side of the stream also implements an isWritable() method. Unless this is a half-open duplex stream, they SHOULD usually have the same return value.

Return values
bool

isWritable()

Checks whether this stream is in a writable state (not closed already).

public isWritable() : bool

This method can be used to check if the stream still accepts writing any data or if it is ended or closed already. Writing any data to a non-writable stream is a NO-OP:

assert($stream->isWritable() === false);

$stream->write('end'); // NO-OP
$stream->end('end'); // NO-OP

A successfully opened stream always MUST start in writable mode.

Once the stream ends or closes, it MUST switch to non-writable mode. This can happen any time, explicitly through end() or close() or implicitly due to a remote close or an unrecoverable transmission error. Once a stream has switched to non-writable mode, it MUST NOT transition back to writable mode.

If this stream is a DuplexStreamInterface, you should also notice how the readable side of the stream also implements an isReadable() method. Unless this is a half-open duplex stream, they SHOULD usually have the same return value.

Return values
bool

listeners()

public listeners([mixed $event = null ]) : mixed
Parameters
$event : mixed = null

on()

public on(mixed $event, callable $listener) : mixed
Parameters
$event : mixed
$listener : callable

once()

public once(mixed $event, callable $listener) : mixed
Parameters
$event : mixed
$listener : callable

pause()

Pauses reading incoming data events.

public pause() : void

Removes the data source file descriptor from the event loop. This allows you to throttle incoming data.

Unless otherwise noted, a successfully opened stream SHOULD NOT start in paused state.

Once the stream is paused, no futher data or end events SHOULD be emitted.

$stream->pause();

$stream->on('data', assertShouldNeverCalled());
$stream->on('end', assertShouldNeverCalled());

This method is advisory-only, though generally not recommended, the stream MAY continue emitting data events.

You can continue processing events by calling resume() again.

Note that both methods can be called any number of times, in particular calling pause() more than once SHOULD NOT have any effect.

Tags
see
self::resume()

pipe()

Pipes all the data from this readable source into the given writable destination.

public pipe(WritableStreamInterface $dest[, array<string|int, mixed> $options = array() ]) : WritableStreamInterface

Automatically sends all incoming data to the destination. Automatically throttles the source based on what the destination can handle.

$source->pipe($dest);

Similarly, you can also pipe an instance implementing DuplexStreamInterface into itself in order to write back all the data that is received. This may be a useful feature for a TCP/IP echo service:

$connection->pipe($connection);

This method returns the destination stream as-is, which can be used to set up chains of piped streams:

$source->pipe($decodeGzip)->pipe($filterBadWords)->pipe($dest);

By default, this will call end() on the destination stream once the source stream emits an end event. This can be disabled like this:

$source->pipe($dest, array('end' => false));

Note that this only applies to the end event. If an error or explicit close event happens on the source stream, you'll have to manually close the destination stream:

$source->pipe($dest);
$source->on('close', function () use ($dest) {
    $dest->end('BYE!');
});

If the source stream is not readable (closed state), then this is a NO-OP.

$source->close();
$source->pipe($dest); // NO-OP

If the destinantion stream is not writable (closed state), then this will simply throttle (pause) the source stream:

$dest->close();
$source->pipe($dest); // calls $source->pause()

Similarly, if the destination stream is closed while the pipe is still active, it will also throttle (pause) the source stream:

$source->pipe($dest);
$dest->close(); // calls $source->pause()

Once the pipe is set up successfully, the destination stream MUST emit a pipe event with this source stream an event argument.

Parameters
$dest : WritableStreamInterface
$options : array<string|int, mixed> = array()
Return values
WritableStreamInterface

$dest stream as-is

removeAllListeners()

public removeAllListeners([mixed $event = null ]) : mixed
Parameters
$event : mixed = null

removeListener()

public removeListener(mixed $event, callable $listener) : mixed
Parameters
$event : mixed
$listener : callable

resume()

Resumes reading incoming data events.

public resume() : void

Re-attach the data source after a previous pause().

$stream->pause();

Loop::addTimer(1.0, function () use ($stream) {
    $stream->resume();
});

Note that both methods can be called any number of times, in particular calling resume() without a prior pause() SHOULD NOT have any effect.

Tags
see
self::pause()

write()

Write some data into the stream.

public write(mixed|string $data) : bool

A successful write MUST be confirmed with a boolean true, which means that either the data was written (flushed) immediately or is buffered and scheduled for a future write. Note that this interface gives you no control over explicitly flushing the buffered data, as finding the appropriate time for this is beyond the scope of this interface and left up to the implementation of this interface.

Many common streams (such as a TCP/IP connection or file-based stream) may choose to buffer all given data and schedule a future flush by using an underlying EventLoop to check when the resource is actually writable.

If a stream cannot handle writing (or flushing) the data, it SHOULD emit an error event and MAY close() the stream if it can not recover from this error.

If the internal buffer is full after adding $data, then write() SHOULD return false, indicating that the caller should stop sending data until the buffer drains. The stream SHOULD send a drain event once the buffer is ready to accept more data.

Similarly, if the stream is not writable (already in a closed state) it MUST NOT process the given $data and SHOULD return false, indicating that the caller should stop sending data.

The given $data argument MAY be of mixed type, but it's usually recommended it SHOULD be a string value or MAY use a type that allows representation as a string for maximum compatibility.

Many common streams (such as a TCP/IP connection or a file-based stream) will only accept the raw (binary) payload data that is transferred over the wire as chunks of string values.

Due to the stream-based nature of this, the sender may send any number of chunks with varying sizes. There are no guarantees that these chunks will be received with the exact same framing the sender intended to send. In other words, many lower-level protocols (such as TCP/IP) transfer the data in chunks that may be anywhere between single-byte values to several dozens of kilobytes. You may want to apply a higher-level protocol to these low-level data chunks in order to achieve proper message framing.

Parameters
$data : mixed|string
Return values
bool

        
On this page

Search results