A simple socketio server for Laravel.
Require php package predis.
Require php extension swoole.
Via Composer
$ composer require folospace/socketio
$ php artisan socketio start //start server
$ php artisan socketio start --d //start server daemonize
$ php artisan socketio stop //stop server
$ php artisan socketio status //server status
namespace App\Providers;
use Folospace\Socketio\Facades\Socketio;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
if (php_sapi_name() == 'cli') {
Socketio::on('connection', function ($socket, $request) {
print_r($request);
echo 'connection:'.$socket->id.PHP_EOL;
});
Socketio::on('disconnect', function ($socket) {
echo 'disconnect:'.$socket->id.PHP_EOL;
//$this->onLogout($socket->id);
});
Socketio::on('login', function ($socket, $data) {
$userId = $data['token']; //parse user id from client token
if ($userId) {
//Socketio::login($socket->id, $userId);
$socket->emit('login', ['error_code' => 0, 'message' => 'login success']);
} else {
$socket->emit('login', ['error_code' => 1, 'message' => 'invalid token']);
}
});
Socketio::on('test', function ($socket, $data) {
$socket->emit('test', 'hello there');
});
Socketio::on('private_event_with_ack', function ($socket, $data, $ack) {
if (Socketio::getUserIdByClient($socket->id)) {
//do sth after login.
if ($ack) {
$ack('done');
}
} else {
//disconnect guest.
$socket->disconnect();
}
});
}
}
}
use Folospace\Socketio\Facades\Socketio;
//after socket login, send data to user from anywhere
Socketio::emitToUser($userId, 'test', ['message' => 'I am server']);
//after server start, connect to local server
Route::get('/', function () {
$client = new \Folospace\Socketio\Foundation\SocketioClient('127.0.0.1', 3001);
$client->emit('test', 'hello');
//sleep(3);
$ret = $client->receive();
dd($ret);
});
$ php artisan vendor:publish --provider="Folospace\Socketio\SocketioServiceProvider"
Please see the changelog for more information on what has changed recently.
Please see contributing.md for details and a todolist.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
MIT. Please see the license file for more information.