Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
<?php Swoole\Server->on('Close', Callable $callback)
The event callback name.
Callable event function.
If success, it returns true
, otherwise it returns false
.
Execute the callback function when the Server is closing a new connection.
It is possible to determine if the server or client closed the connection, within the Close
event callback, the reactor thread ID is passed, if this argument is -1
then it means the server closed the connection, if it is above 0
then the client closed the connection. So you can perform $reactorId < 0
within an if statement to see who closed the connection.
If you have TCP heartbeat polling setup, if a connection is closed due to being idle, the reactor ID will not be -1
.
<?php
$server = new Swoole\Server("127.0.0.1", 9501);
$server->on('Start', function($server)
{
echo "Server is started.\n";
});
$server->on('Shutdown', function($server)
{
echo "Server is shutting down.\n";
});
$server->on('Connect', function($server, $fd)
{
echo "New connection established: #{$fd}.\n";
});
$server->on('Receive', function($server, $fd, $reactorId, $data)
{
$server->send($fd, "Echo to #{$fd}: \n".$data);
$server->close($fd);
});
$server->on('Close', function($server, $fd, $reactorId)
{
echo "Connection closed: #{$fd}.\n";
});
$server->start();
$server
: The Swoole server object$fd
: The ID number of client$reactorId
: The ID number of reactor thread, when the $reactorId < 0
, the connection is closed by server.If a fatal error occurs within the Close
callback, it will cause a memory leak due to connections being in a CLOSE_WAIT
state
Both a connection being closed by the server or client, it will trigger the Close
event callback
You can still use the Swoole\Server->getClientInfo
method to access information about the client that was connected
When this callback is executed it means the connection has already been closed, so you don't need to call $server->close($fd)
otherwise it will throw a warning