Cooperate with the supervisor to create a websocket server in laravel using swoole

Time:2021-8-28

I want to implement a chat room with wesocket. I see that swoole supports this very well on the Internet, so I tried to combine laravel with swoole. I just made an attempt and it can run successfully. The specific details are not yet perfect.

1. Please refer to the official website documentation for the installation of swoole

https://wiki.swoole.com/

2. Refer to the recent manual to create a new command in laravel, swoole

http://laravelacademy.org/post/6842.html

Create a command called spoolphp artisan make:command Swoole

Add command list in kernel.php

protected $commands = [
        Commands\Swoole::Class
];

Modify the swoole file as follows:

<? php

This time you canphp artisan listI found the swoole command in the. See the manual for details.

3. Detailed interpretation

a. Swoole of swoole is called in the start() function_ websocket_ The server class creates a websocket server to listen on port 9502

b. For several events, please refer to the official Manual of swoole. In fact, it is to listen to a socket connection and respond to messages. This is the prototype of a chat room. You can use any function of laravel to locate the user’s chat room and send messages to everyone to form a real-time chat function

c. For example, when the user logs in and sends a message, a rid (chat room) is attached. The program corresponds FD to rid and broadcasts messages to all FD corresponding to rid

4. It is best to use supervisor to guard the spoole command and keep it running in the background

My configuration is as follows:

[program:swoole-worker]

5. Realize the chat function in HTML. You can only chat with yourself. Try a long connection. If you want to combine the program, please try it yourself~

<! DOCTYPE html>

Thank you for creating so many useful libraries and extensions

This work adoptsCC agreement, reprint must indicate the author and the link to this article