duan6301 2017-02-19 21:50
浏览 684
已采纳

为什么使用redis进行websocket通信?

Please help me clear up some confusion.

Laravel allows communication with socket.io by having you set up redis:

https://laravel.com/docs/5.4/broadcasting#configuration

To my understanding Redis simply holds the data in memory something similar to memcached? This allows third party software like socket.io to pick up the data. Is this really websocket behaviour though?

I know that you can also do something like this in PHP:

$address = 'localhost';
$port = 5600;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $address, $port);

Why wouldn't they choose to something above instead of having you set up Redis? There is probably a good answer to this but I don't have that much experience with either Redis or websockets.

Any information on this would be appreciated.

  • 写回答

1条回答 默认 最新

  • duanbei3704 2017-02-20 01:27
    关注

    You need to think about persistance of connection. A Request in Laravel only lives for the time it takes to get a response out. Once response is sent back, application shuts down until a new request hits the index.php and Laravel boots again.

    So in fact, you can not establish a persistant connection this way. Socket.io for example, will let you connect to the service and remain connected. This is the main difference between a Rest and Websocket approach. In a Rest interface, the client continually polls the server... So if you have 1000 clients you have 1000 pesky little clients asking you if you have anything new every 30 seconds... annoying at best. But each time they ask, Laravel goes through the whole boot/shutdown process... nothing is persistant.

    Now when using Socket.io through a Node service, each client will connect and have a persistant connection to the Node instance (which is a single persistant thread... better suited for this)... Having this connection to the 1000 clients, the clients simply listen to the socket for something new...

    When a Laravel request creates an event that is of interest to the 1000 clients, it simply pushes the information to Redis queue... The Node instance reads from the Redis queue and can broadcast to the 1000 connected client as it has maintained the connection...

    It is a nice use of both PHP and Node technology as it highlights the strengths of both...

    Hope this helps...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵