【问题标题】:Laravel echo with socket.ioLaravel 与 socket.io 的回声
【发布时间】:2017-05-28 12:19:41
【问题描述】:

我想在 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 服务器运行成功,没有任何错误。

谢谢,

帕斯·沃拉

【问题讨论】:

  • 你的ws连接服务器成功了吗?
  • @CerlinBoss 是的
  • ws 连接中的框架呢?你收到了吗?
  • 每当我重新加载任何页面时,我都会在控制台上收到此消息:[4:02:50 PM] - 7X4kQ2-fMdicrTp_AAAC 加入频道:new-vote [4:02:50 PM] - 7X4kQ2 -fMdicrTp_AAAC 左声道:新投票
  • 这意味着它工作正常。

标签: laravel websocket socket.io laravel-5.3 laravel-echo


【解决方案1】:

配置 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()) 这样的事件时,请确保 Echo 配置了命名空间 Hello.World

干杯!

【讨论】:

  • 我使用这个命令安装了 npm 包。 npm install 然后在资源\assets\js 中的 bootstrap.js 中启用这一行 import Echo from 'laravel-echo'。我收到一条错误消息,提示 Cannot find module "laravel-echo" 我需要为此安装任何东西吗?我正在使用 echo 在 laravel Blade 中学习 socket.io
【解决方案2】:

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

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

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

可能会帮助某人。

【讨论】:

  • 嗨。我的朋友,你的 github 链接已经死了,你能重现它吗?
【解决方案3】:
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 工匠服务

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 2018-03-03
    • 2018-05-30
    • 2016-02-15
    • 2017-10-11
    • 2017-01-02
    • 2021-06-18
    • 2020-01-01
    • 1970-01-01
    相关资源
    最近更新 更多