search
HomeBackend DevelopmentPHP TutorialPHP asynchronously calls socket implementation code_PHP tutorial

PHP asynchronously calls socket implementation code_PHP tutorial

Jul 21, 2016 pm 03:21 PM
phpsocketcodeandaccomplishasynchronousWayserverBrowsertransferFor

PHP asynchronous call implementation method
There is only one connectionless HTTP protocol for communication between the browser and the server. The characteristic of the connectionless program is that the client requests the server, and the server The program requesting the output of the corresponding program cannot maintain a persistent connection.
A problem arises. The corresponding server of a client may execute for 1 second or for 1 minute. In this way, the browser will always be in a waiting state. If the program executes slowly, the user may not have the patience to turn off browsing. device.
Sometimes we don’t need to care about the results of program execution. There is no need to waste time and wait patiently like this. Then we have to find a way to make the program execute silently in the background without waiting.
For example, there is a scenario where a recommendation email is sent to 1,000 users. The user enters or imports the email account and submits it to the server for sending.

Copy code The code is as follows:

$count=count($emailarr);
for($i=0;$i{
 sendmail(.....);//Send email
}
?>

This code has a very poor user experience and cannot be used in practice. First of all, sending so many emails will cause the server to run timeout. In fact, the long user waiting time will make users doubt and lose confidence in the system product. However, the user does not need to wait until all 1,000 emails have been sent before submitting the message successfully. We can directly prompt the user to send it successfully after submitting it to the background, and then let the background program silently send it one by one.
At this time we need "asynchronous execution" technology to execute the code. The characteristic of asynchronous execution is silent execution in the background. The user does not need to wait for the execution result of the code. The benefits of using asynchronous execution:
1. Get rid of the application control Dependency of a single task
2. Improve the execution efficiency of the program
3. Improve the scalability of the program
4. Improve the user experience in certain scenarios
5. Because PHP does not support multi-threading , using asynchronous calls to request multiple HTTPs achieves the effect of parallel program execution, but please note that if too many HTTP requests are requested, the system overhead will be greatly increased
Common methods for PHP asynchronous execution:
1. The client page uses AJAX technology to request the server
1. The simplest way is to embed an AJAX call in the HTML code returned to the client, or embed a img tag, src points to the time-consuming script to be executed.
This method is the simplest and fastest. The server does not need to make any calls.
But the disadvantage is that generally speaking, Ajax should be triggered after onLoad. That is to say, if the user clicks on the page and then closes it, our background script will not be triggered.
If you use the img tag, this method cannot be called asynchronous execution in the strict sense. The user's browser will wait for a long time for the execution of the php script to be completed, that is, the status bar of the user's browser always shows that it is still loading.
Of course, you can also use other methods with similar principles, such as script tags, etc.
2.popen() function
resource popen ( string command, string mode );
//Open a pipe pointing to the process spawned by the execution of the given command command. Opens a pipe to the process spawned by execution of the command that spawned the given command.
So you can call it but ignore its output.
pclose(popen("/home/xinchen/backend.php &", 'r'));
This method avoids the shortcomings of the first method and is also fast. But the problem is that this method cannot request another WebService through the HTTP protocol and can only execute local script files. And it can only be opened in one direction, and cannot pass a large number of parameters to the called script.
And if the number of visits is high, a large number of processes will be generated. If you use external resources, you have to consider the competition yourself.
3.CURL extension
CURL is a powerful HTTP command line tool that can simulate HTTP requests such as POST/GET, and then get and extract data and display it in "standard output" (stdout) Copy the code above
and the code is as follows:
$ch = curl_init();
$curl_opt = array(CURLOPT_URL, 'http://www.example.com/backend.php',
CURLOPT_RETURNTRANSFER, 1,
CURLOPT_TIMEOUT, 1,);
curl_setopt_array($ch, $curl_opt);
curl_exec($ ch);
curl_close($ch);


Using CURL requires setting CUROPT_TIMEOUT to 1 (the minimum is 1, depressing). That is, the client must wait at least 1 second.

4.fscokopen() function
fsockopen is a very powerful function that supports socket programming. You can use fsockopen to implement socket programs such as email sending, etc. To use fcockopen, you need to manually splice out the header. Part of the
official document: http://cn.php.net/fsockopen/


Copy code The code is as follows:

$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno )
n";
} else {
$out = "GET /backend.php / HTTP/1.1rn";
$out .= "Host: www.example.comrn ";
$out .= "Connection: Closernrn";
fwrite($fp, $out);
/*Ignore the execution result
while (!feof($fp)) {
echo fgets($fp, 128);
}*/
fclose($fp);
}

PHP asynchronously calls socket
Copy code The code is as follows:


$host = "www.aaa.com";
$path = "/Report.php?ReportID=1";
$cookie = Session_id();
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
print "$errstr ($errno)
n";
exit;
}
$out = "GET ".$path." HTTP /1.1rn";
$out .= "Host: ".$host."rn";
$out .= "Connection: Closern";
$out .= "Cookie: ".$ cookie."rnrn";
fwrite($fp, $out); //Write the request to the socket
//You can also choose to get the response from the server
/*while (!feof($fp) ) {
echo fgets($fp, 128);
}*/
//If you don’t wait for the server-side response, just close the socket directly
fclose($fp);
?> ;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324937.htmlTechArticlePHP asynchronous call implementation method There is only a connectionless HTTP protocol for communication between the browser and the server. The characteristic of a connectionless program is that the client requests the server, and the server...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.