This is how I have done in Laravel, You need to install Predis , socket.io , ratchet and other dependencies . Please check https://laracasts.com/discuss/channels/general-discussion/step-by-step-guide-to-installing-socketio-and-broadcasting-events-with-laravel-51
Make one custom artisan command to run a websockets on some port using ratchet
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Ratchet\Server\IoServer;
class webSockets extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'run:socket {port?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run websockets for specified port';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$port = $this->argument('port');
$server = IoServer::factory(
new ChatController(),$port
$server->run();
}
}
Your controller should be like below
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class ChatController implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {
}
public function onMessage(ConnectionInterface $from, $msg) {
//FIRE A BROADCAST EVENT HERE
event(new MessageBroadcast(
$message,
$datetime,
$user_id
)
);
}
public function onClose(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, \Exception $e) {
}
}
THE BROADCAST CLASS SHOULD LOOK LIKE BELOW
namespace App\Events;
use App\Events\Event;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class MessageBroadcast extends Event implements ShouldBroadcast
{
use SerializesModels;
public $message,$datetime,$userid;
public function __construct($message,$datetime,$userid)
{
$this->message = $message;
$this->datetime = $datetime;
$this->userid = $userid;
}
public function broadcastOn()
{
return ['test-channel'.$this->user_id];
}
}
Javascript part to subscribe a channel
<script src="{ { asset('js/socket.io.js') } }"></script>
<script>
//var socket = io('http://localhost:3000');
var socket = io('http://yourip:5000');
socket.on("test-channel1:App\\Events\\EventName", function(message){
// get user on console
console.log(message);
});
</script>
You need to run following command in backgroud
1. php artisan run:socket <port_no>
2. Node yourjavascript.js