Last active
March 10, 2019 09:54
-
-
Save bsaqqa/ff0d2fa6185ce28c69ab0f4e48a69b9e to your computer and use it in GitHub Desktop.
socket.io php for laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// For laravel lunch | |
define('LARAVEL_START', microtime(true)); | |
require_once __DIR__ . '/vendor/autoload.php'; | |
$app = require_once __DIR__ . '/bootstrap/app.php'; | |
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class); | |
$response = $kernel->handle( | |
$request = Illuminate\Http\Request::capture() | |
); | |
// Install packages from (https://github.com/walkor/phpsocket.io) | |
use Workerman\Worker; | |
use PHPSocketIO\SocketIO; | |
use \App\Models\Message; | |
use Illuminate\Http\Request; | |
// listen port 2021 for socket.io client | |
$io = new SocketIO(2021); | |
// for allow origins (Cors) | |
$io->origins('*:*'); | |
$io->on('connection', function($socket)use($io){ | |
// listener at "$room" room | |
$socket->on('room', function ($room) use ($socket, $io) { | |
// for make serve rooms/private chats; | |
$socket->join($room); | |
// listener at "chat message" channel | |
$socket->on('chat message', function ($msg) use ($io, $socket , $room) { | |
try{ | |
// save message at DB by use eloquent model | |
$message = Message::create([ | |
"body" => $msg['body'], | |
"chatroom_id" => $msg['chatroom'], | |
"user_id" => $msg['user'], | |
"type" => $msg['type'] | |
]); | |
// for broadcasting message | |
$socket->in($room)->emit('chat message', $msg); | |
$socket->emit('chat message', $msg); | |
} catch (Exception $e) { | |
echo 'Caught exception: ', $e->getMessage(), "\n"; | |
} | |
}); | |
echo "connection ..\n"; | |
}); | |
}); | |
Worker::runAll(); | |
// To Run Socket at local: | |
// php socket.php start -d | |
// To Run Socket at server: | |
// nohup php socket.php start -d > /dev/null & |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment