1. Go to this page and download the library: Download cydrickn/socketio library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
cydrickn / socketio example snippets
$server = new \Cydrickn\SocketIO\Server([
'host' => '0.0.0.0',
'port' => 8000,
'mode' => SWOOLE_PROCESS,
'settings' => [
\Swoole\Constant::OPTION_WORKER_NUM => swoole_cpu_num() * 2,
\Swoole\Constant::OPTION_ENABLE_STATIC_HANDLER => true,
]
]);
$server->on('Started', function (\Cydrickn\SocketIO\Server $server) {
echo 'Websocket is now listening in ' . $server->getHost() . ':' . $server->getPort() . PHP_EOL;
});
$server->on('connection', function (\Cydrickn\SocketIO\Socket $socket) {
// ...
});
$server->start();
$server->on('connection', function (\Cydrickn\SocketIO\Socket $socket) {
$socket->emit('hello', 'world');
});
$socket->emit('hello', 'world', 1, 2, 3, 'more');
// BAD
$socket->emit('hi', json_encode(['name' => 'Juan']));
// GOOD
$socket->emit('hi', ['name' => 'Juan']);
// timeout for 5 seconds
$socket->timeout(5000)->emit('hi', function (bool $err) {
if ($err) {
// the other side did not acknowledge the event in the given delay
}
});
// timeout for 5 seconds
$socket->timeout(5000, 'Juan')->emit('hi', function (bool $err, string $name) {
var_dump($name); // if the other side did not acknowledge the event the $name will be 'Juan'
if ($err) {
// the other side did not acknowledge the event in the given delay
}
});
$server->on('hello', function (\Cydrickn\SocketIO\Socket $socket, string $world) {
// ...
});
$server->on('hi', function (\Cydrickn\SocketIO\Socket $socket, array $name) {
// ...
});