4

我想在 javascript 端监听服务器端事件。我为此找到了这个包:

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

如果这么多次,我已经阅读了所有内容:

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

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

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

到目前为止,我已经这样做了:

控制器动作:

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

“NewVote”事件类:

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": ""
}

此命令已在运行:

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

当我触发事件时,我期待控制台按摩。但我没有在控制台上得到任何东西。

让我知道是否需要任何其他信息。

注意:我的 socket.io 服务器运行成功,没有任何错误。

谢谢,

帕思·沃拉

4

3 回答 3

3

配置 Echo 花了我一段时间,但我发现客户端配置包含一个令人困惑的默认事件命名空间。

尝试如下配置 Echo 客户端库:

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'
});

因此,当触发这样的事件时event(new \Hello\World\NewVote()),请确保使用命名空间配置 EchoHello.World

干杯!

于 2017-01-13T15:33:24.660 回答
3

不知道是什么问题。但最后,我让它工作。

我还创建了一个小演示,它说明了使用 laravel-echo-server ( https://github.com/tlaverdure/laravel-echo-server ) 将 Laravel echo 与 socket.io 一起使用。

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

可能会帮助某人。

于 2017-01-20T13:41:39.097 回答
0
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/bootstrap@5.0.0-beta3/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');
});

现在通过终端运行你的节点服务器

节点服务器.js

现在提供你的 laravel 文件

php工匠服务

于 2022-01-20T12:52:43.850 回答