don't want use Laravel Echo ?
Apr 23, 2017
10
Level 2
Socket.io not working with Event
Hi, look at the below codes -
//socket.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('redirect-to', function(err, count) {
});
redis.on('message', function(channel, message) {
console.log('Message Recieved: ' + message);
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
http.listen(function(){
console.log('Listening on Port');
});
In a view file i've the blow codes
@extends('layouts.admin_tpl')
@section('content')
<h3>
Redirect To
</h3>
<hr/>
<div class="row">
<div class="col-12" id="power">
</div>
</div>
<script src="{{ asset('js/socket.io.min.js') }}"></script>
<script>
var url = window.location.hostname+ ':3000';
var socket = io('{{url("/")}}');
var socket = io('{{route("admin_redirectto")}}');
socket.on("redirect-to:App\\Events\\RedirectTo", function(message){
$('#power').text(message.data.url);
console.log('inside the socket');
});
</script>
@endsection
RedirectTo event's code -
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class RedirectTo
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $data;
public function __construct()
{
$this->data = [
'addition' => '10'
];
}
public function broadcastOn()
{
// return new PrivateChannel('redirect-to');
return ['redirect-to'];
}
}
Route
Route::get('admin/redirectto', 'AdminController@redirectTo_get')->name('admin_redirectto');
Route's controller function -
public function redirectTo_get(Request $request)
{
// $data = [
// 'event' => 'RedirectTo',
// 'data' => [
// 'url' => 'http://zahedkamal.com',
// 'name' => 'Zahed Kamal'
// ]
// ];
// Redis::publish('redirect-to', json_encode($data));
event(new RedirectTo());
return view('admin.redirectto');
}
I've the laravel project/app running using xampp in c:/xampp/htdocs/larapro. So, i visit the url
http://localhost:8080/larapro/public/admin/redirectto
//OR
http://localhost:8000/admin/redirectto //using "php artisan serve" command
I get the below error
http://localhost:8080/socket.io/ [HTTP/1.1 404 Not Found 12ms]
//OR
http://localhost:8000/socket.io/ [HTTP/1.1 404 Not Found 12ms]
Everytime i visit the url Note that if i disable the 'event(new RedirectTo())` and un-comment the codes above above that line. I get logs in CMD.
Please advice me how can i get it working. Or what i am doing wrong. Thank you
Please or to participate in this conversation.