Table of Contents
Official documentation
Install phpsocketio
Service entry file
Server.php
Home PHP Framework ThinkPHP The process of integrating phpsocketio with thinkphp5 was a pitfall that I personally stepped on!

The process of integrating phpsocketio with thinkphp5 was a pitfall that I personally stepped on!

Aug 31, 2021 pm 04:37 PM
php socket.io thinkphp5

thinkphp The framework tutorial column will introduce you to the complete guide on integrating phpsocketio with thinkphp 5.0. I hope it will be helpful to friends in need!

thinkphp 5.0 complete guide to integrating phpsocketio, avoiding pitfalls

Usage environment: thinkphp5.0

projectRequirements

The front-end places an order, and the back-end accepts it and prompts it immediately. For example: Meituan Takeaway, after the client successfully places an order, the merchant will immediately have a voice prompt for receiving the order.

Development environment

  • thinkphp5.0
  • phpsocketio

(Since the socket service needs to be started, It needs to be used in an environment that can satisfy the shell)

socketio Advantages

This is just my opinion. After all, I haven’t studied socketio in depth, so I just give a brief summary:

  • Reduce server IO load
  • Long connection ratioajaxPolling is reliable
  • The service is stable and supports dynamic

After a brief look, the memory usage is very small, and there is only one process. According to official reports, one process can also accommodate high concurrency of 10,000 people, so it is more than enough for my project.

Official documentation

https://github.com/walkor/php...

Start development

Install phpsocketio

First cd to the project root directory of thinkphp. Use the following command

composer require workerman/phpsocket.io
Copy after login

(Composer will not explain here. If there is any problem, please ask me and it should be solved)

After installation, vendor There should be a workerman folder under the folder. If it exists, congratulations, it has been installed.

Service entry file

Go back to the project root directory and create a newsocketio.php, start editing

#!/usr/bin/env php
<?php
define(&#39;APP_PATH&#39;, __DIR__ . &#39;/application/&#39;);
define(&#39;BIND_MODULE&#39;,&#39;socketio/Server/index&#39;);
// 加载框架引导文件
require __DIR__ . &#39;/thinkphp/start.php&#39;;
Copy after login

Just write it here and it will be OK. For all subsequent things, you can ignore his existence

Create service controller

In the socketio.php file in the previous step, module binding When we get to 'socketio/Server/index', we need to create it manually. In order to understand, I use the directory to display

├─application           应用目录
│  ├─socketio           新创建目录
│  │  ├─controller      
│  │  │  ├─Server.php   启动文件
Copy after login

Server.php

The entry file is only bound to this controller, so this is the core of the entire socketio.

<?php
/*
 * (c) U.E Dream Development Studio
 *
 * Author: 李益达 - Ekey.Lee <ekey.lee@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace app\socketio\controller;

require_once VENDOR_PATH . "workerman/phpsocket.io/src/autoload.php";

use PHPSocketIO\SocketIO;
use Workerman\Worker;

class Server
{

    public function index()
    {
        $io = new SocketIO(8080);//socket的端口
        $io->on('workerStart', function () use ($io) {
            $inner_http_worker = new Worker('http://0.0.0.0:5880');//这里IP不用改变,用的内网通讯,端口不能与socket端口想通
            $inner_http_worker->onMessage = function ($http_connection, $data) use ($io) {
                
                $io->emit('new_msg', '44444');//这里写了固定数据,请根据自己项目需求去做调整,不懂这里的可以看看官方文档,很清楚
                $http_connection->send('ok');
            };
            $inner_http_worker->listen();
        });

        // 当有客户端连接时
        $io->on('connection', function ($socket) use ($io) {
            // 定义chat message事件回调函数
            $socket->on('chat message', function ($msg) use ($io) {
                // 触发所有客户端定义的chat message from server事件
                $io->emit('chat message from server', $msg);
            });
        });

        Worker::runAll();
    }
}
Copy after login

Create API to trigger socketio

Similarly you can create a new API controller under socketio, this is only for testing

 public function api()
    {
        // 推送的url地址,使用自己的服务器地址
        $push_api_url = "http://0.0.0.0:5880";//这里同样不需要更改IP。只是端口一定需要和server.php onworker的一样
        $post_data = array(
           "type" => "publish",
           "content" => "这个是推送的测试数据",
        );
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
        $return = curl_exec ( $ch );
        curl_close ( $ch );
        var_export($return);
    }
Copy after login

Now thereserverServer side, API trigger side, then it needs to be displayed, which is our front end

Front end

What I want to write now is the prompt received by the merchant. The previously written server server provides phpsocketio monitoring and socket services, and API provides event triggering, that is, the trigger after someone places an order. The order is used as an event to trigger the server socket, allowing him to Respond to the front-end

Please note before starting the code: the port and domain name here are roundabout

 <script src=&#39;//cdn.bootcss.com/socket.io/1.3.7/socket.io.js&#39;></script>
  <script>
            // 连接服务端
            var socket = io('http://xxxx.com:8080');//这里请填写你的域名,外网,端口为socket端口
          // 后端推送来消息时
            socket.on('new_msg', function (msg) {//这里的new_msg请一定要注意,官方文档都写的是content,但是后端发送的自定义是new_msg,后端定义成new_msg,前端却接受content的字段。所以是接受不了的
                swal({ title: "包厢点餐提醒", text: "哆啦a梦包厢有新订单" })
                //console.log("收到消息:" + msg);
            });

</script>
Copy after login

There are two places where I had problems before

  • Port Domain name: The domain name is the domain name of the external network. Of course, it needs to be under the same IP as your socket service, that is: your socket is deployed under the IP of 114.114.114.114. This domain name must be under the IP of 114.114.114.114. The port is the port of new SocketIO in the backend service.
  • socket.on()The document contains socket.on('content',function(msg){....}), but you can read it In our Server.php $io->emit('new_msg', '');The custom event here is clearly called new_msg, but it is written as content , maybe I am blind and did not see it clearly, but I would also like to remind you that you must pay attention to the callback event name

After deployment, start running

Now that all files are deployed, enter server management and open shell. cdGo to the project root directory. Then execute

php socketio.php start
Copy after login
#php socketio.php start Start
#php socketio.php stop
Stop
php socketio.php restart
Restart
##php socketio. php status Current service statusSummary

This time is only a work summary, because I was pressed for time and did not do a good job To study more about socketio, there may be some flaws, but I 100% guarantee that this was tested by me personally, and the pitfalls mentioned were all overcome by me step by step. If there is anything wrong, please let me know ^_^

The above is the detailed content of The process of integrating phpsocketio with thinkphp5 was a pitfall that I personally stepped on!. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles