Home Backend Development PHP Tutorial Using laravel+Swoole to implement websocket active message push

Using laravel+Swoole to implement websocket active message push

Nov 29, 2019 pm 04:36 PM
websocket Push message

Recently there is a demand: I want to implement a function that can actively trigger message push. This can be used to send custom messages to template messages to all members without sending messages through the client. In message, the transmitted message is monitored and the corresponding business logic is performed.

Using laravel+Swoole to implement websocket active message push

Active message push implementation

Usually we use swoole to writeWebSocket The service may use the three listening states of open, message, and close the most, but never look at the use of the onRequest callback below. Yes, this is what is needed to solve this active message push. Use onRequest callback.

Official document: Because swoole_websocket_server inherits from swoole_http_server, there is an onRequest callback in websocket.

Detailed implementation:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

# 这里是一个laravel中Commands

# 运行php artisan swoole start 即可运行

<?php

 

namespace App\Console\Commands;

 

use Illuminate\Console\Command;

use swoole_websocket_server;

 

class Swoole extends Command

{

    public $ws;

    /**

     * The name and signature of the console command.

     *

     * @var string

     */

    protected $signature = &#39;swoole {action}&#39;;

 

    /**

     * The console command description.

     *

     * @var string

     */

    protected $description = &#39;Active Push Message&#39;;

 

    /**

     * Create a new command instance.

     *

     * @return void

     */

    public function __construct()

    {

        parent::__construct();

    }

 

    /**

     * Execute the console command.

     *

     * @return mixed

     */

    public function handle()

    {

        $arg = $this->argument(&#39;action&#39;);

        switch ($arg) {

            case &#39;start&#39;:

                $this->info(&#39;swoole server started&#39;);

                $this->start();

                break;

            case &#39;stop&#39;:

                $this->info(&#39;swoole server stoped&#39;);

                break;

            case &#39;restart&#39;:

                $this->info(&#39;swoole server restarted&#39;);

                break;

        }

    }

 

    /**

     * 启动Swoole

     */

    private function start()

    {

        $this->ws = new swoole_websocket_server("0.0.0.0", 9502);

        //监听WebSocket连接打开事件

        $this->ws->on(&#39;open&#39;, function ($ws, $request) {

        });

        //监听WebSocket消息事件

        $this->ws->on(&#39;message&#39;, function ($ws, $frame) {

            $this->info("client is SendMessage\n");

        });

        //监听WebSocket主动推送消息事件

        $this->ws->on(&#39;request&#39;, function ($request, $response) {

            $scene = $request->post[&#39;scene&#39;];       // 获取值

            $this->info("client is PushMessage\n".$scene);

        });

        //监听WebSocket连接关闭事件

        $this->ws->on(&#39;close&#39;, function ($ws, $fd) {

            $this->info("client is close\n");

        });

        $this->ws->start();

    }

}

Copy after login

What I mentioned above is the implementation of onRequest in swoole. The following implementation actively triggers the onRequest callback in the controller. The implementation method is the curl request we are familiar with.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

# 调用activepush方法以后,会在cmd中打印出

# client is PushMessage 主动推送消息 字眼

    /**

     * CURL请求

     * @param $data

     */

    public function curl($data)

    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, "http://127.0.0.1:9502");

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($curl, CURLOPT_HEADER, 1);

        curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        curl_exec($curl);

        curl_close($curl);

    }

     

    /**

     * 主动触发

     */

    public function activepush()

    {

        $param[&#39;scene&#39;] = &#39;主动推送消息&#39;;

        $this->curl($param);            // 主动推送消息

Copy after login

Purpose
onRequest callback is especially suitable for push messages that need to be called in the controller, such as template messages, etc., which are called in the controller.

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of Using laravel+Swoole to implement websocket active message push. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

The combination of Java and WebSocket: how to achieve real-time video streaming The combination of Java and WebSocket: how to achieve real-time video streaming Dec 17, 2023 pm 05:50 PM

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages ​​in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use Java and WebSocket to implement real-time stock quotation push How to use Java and WebSocket to implement real-time stock quotation push Dec 17, 2023 pm 09:15 PM

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.

How does Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

See all articles