Parth Vora
Parth Vora

Reputation: 4114

Laravel echo with socket.io

I want to listen for server side event on javascript side. I found this package for that:

https://github.com/tlaverdure/laravel-echo-server

I have already read all if this so many times:

https://laravel.com/docs/5.3/events

https://laravel.com/docs/5.3/broadcasting

https://laravel.com/docs/5.3/notifications

So far I have done this:

Controller action:

broadcast(new NewVote());
event(new NewVote()); // Also tried this

"NewVote" Event class:

public function broadcastOn()
    {
        return new Channel('new-vote');
    }

Javascript:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://assessment.local:6001'
});

window.Echo.channel('new-vote')
    .listen('NewVote', (e) => {
        console.log(e);
    });

laravel-echo-server.json

{
    "appKey": "0p4o9t942ct15boc4nr8tjb178q29fdmlcat8c1p1s51i2pbq9nmtjud94t4",
    "authHost": null,
    "authEndpoint": "/broadcasting/auth",
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "assessment.local",
    "port": "6001",
    "referrers": [],
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}

Already this commands are running:

laravel-echo-server start
php artisan queue:work
php artisan queue:listen
gulp watch

All I'm expecting a console massage when, I fire the event. But I'm not getting anything on the console.

Let me know if any other information needed.

Note: My socket.io server is running successfully without any error.

Thanks,

Parth Vora

Upvotes: 4

Views: 11098

Answers (3)

aakash rajput
aakash rajput

Reputation: 131

Your blade file looks like this.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Chat app</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
        <!-- CSS only -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
        <style>
            .chat-row {
                margin: 50px;
            }
            ul {
                margin: 0;
                padding: 0;
                list-style: none;

                border-radius: 5px;
            }
            ul li {
                padding:4px;
                background-color: #9fe3e6;
                margin-top: 2vh;
                border-radius: 5px;
            }
            .type-message {
            position: fixed;
            width: 70vw;
            bottom: 0;
            margin-bottom: 4vh;
            }
        </style>
    </head>
    <body>

        <div class="container">
            <div class="row chat-row">
                <div class="chat-content">
                    <ul>

                    </ul>
                </div>
                <div class="type-message">
                    <form onsubmit="return false" action="#">
                        <div class="form-group d-flex">
                            <input type="hidden" name="" id="name" value="{{ Auth::user()->name ?? 'Anonymous'}}">
                            <input type="text" name="" id="message" class="form-control" placeholder="Type message...">
                            <button class="btn btn-primary mx-2" id="sentmessage">Send</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>


        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
        <script src="https://cdn.socket.io/4.0.1/socket.io.min.js" integrity="sha384-LzhRnpGmQP+lOvWruF/lgkcqD+WDVt9fU3H4BWmwP5u5LTmkUGafMcpZKNObVMLU" crossorigin="anonymous"></script>


        <script>
            $(function() {
                let ip_address = '127.0.0.1';
                let socket_port = '3000';
                let socket = io(ip_address + ':' + socket_port);

                $('#sentmessage').on('click',function(){
                    let message_value = $('#message').val();
                    let message = $('#name').val() + ' : &nbsp;' + $('#message').val();
                    let name = $('#name').val();
                    if($.trim(message_value) != '')
                    {
                        socket.emit('sendChatToServer', message);
                        $('.chat-content ul').append('<li>Me : &nbsp;'+ message_value +'</li>');
                        $('#message').val('');
                    }
                })

                socket.on('sendChatToClient', (message) => {
                    $('.chat-content ul').append(`<li>${message}</li>`);
                });
            });
        </script>
    </body>
</html>


Now create a file named server.js in root directory i.e.  your_project/server.js and put this code 

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, {
    cors: { origin: "*"}
});


io.on('connection', (socket) => {
    console.log('connection');

    socket.on('sendChatToServer', (message) => {
        socket.broadcast.emit('sendChatToClient', message);
    });


    socket.on('disconnect', (socket) => {
        console.log('Disconnect');
    });
});

server.listen(3000, () => {
    console.log('Server is running');
});

Now run your node server through terminal

node server.js

and now serve your laravel file

php artisan serve

Upvotes: 0

Parth Vora
Parth Vora

Reputation: 4114

Don't know what was the issue. But finally, I make it working.

I also created a small demo which illustrates the use of Laravel echo with socket.io using laravel-echo-server (https://github.com/tlaverdure/laravel-echo-server).

https://github.com/xparthxvorax/Larevel-echo-with-socket.io

Might help someone.

Upvotes: 3

Eelke van den Bos
Eelke van den Bos

Reputation: 1463

Configuring Echo took me a while, but I found the client side configuration to contain a confusing default event namespace.

Try configuring the Echo client side library as following:

import Echo from "laravel-echo"

window.Echo = new Echo({
    namespace: 'Base.Event.Namespace', //defaults to App.Event
    broadcaster: 'socket.io',
    host: 'http://assessment.local:6001'
});

So when firing an event like so event(new \Hello\World\NewVote()), make sure Echo is configured with the namespace Hello.World

Cheers!

Upvotes: 3

Related Questions