PHP Asynchronous call socket implementation code _php tips

Source: Internet
Author: User
Tags php script mail account
How the asynchronous invocation of PHP is implemented
Browser and the server is only a connectionless HTTP protocol for communication, the characteristics of the connectionless program is the client request server, the server according to the request output corresponding program, can not maintain a durable connection.
As a problem, a client's corresponding server may perform 1 seconds and possibly 1 minutes, so that the browser is always waiting, and if the program executes slowly, the user may not be patient enough to turn off the browser.
And sometimes we do not need to care about the results of the implementation of the program, there is no need to waste time and patience to wait, then we have to figure out ways to let the program do not wait in the background silently execution.
For example, there is a scenario where a referral message is sent to 1000 users, the user enters or imports a mail account, and the submitting server performs the sending.
Copy Code code as follows:

<?php
$count =count ($emailarr);
for ($i =0; $i < $count; $i + +)
{
SendMail (...); /Send mail
}
?>

This Code user experience is very poor, also can not actually use, first send so many messages will produce server running timeout, in fact, long time users to wait for the system product suspicion and loss of confidence. However, the user does not need to wait until 1000 messages have been sent to send a successful delivery, we can fully submit after the background directly to the user prompted to send success, and then let the background program to send silently.
This time we need to "execute asynchronously" technology to execute code, asynchronous execution is characterized by silent background execution, the user does not have to wait for the execution of the code results, the benefits of using asynchronous execution:
1. Get rid of the application's dependency on a single task
2. Increased efficiency in the execution of procedures
3. Improve the program's scalability
4. Improve the user experience in a certain scenario
5. Because PHP does not support multithreading, the use of asynchronous calls to request multiple HTTP to achieve the program in parallel execution effect, but note that the request is too much HTTP, will greatly increase the overhead of the system
common ways to execute PHP asynchronously:
1. The client page uses AJAX technology to request the server
1. The easiest way to do this is to embed Ajax calls into the HTML code that is returned to the client, or embed an IMG tag, and SRC points to the time-consuming script to execute.
This method is the simplest and fastest. The server side does not have to make any calls.
But the disadvantage is, generally speaking, Ajax should be triggered after the onload, that is, the user points to open the page, then close, it will not trigger our background script.
In the case of an IMG tag, this approach cannot be called a strict asynchronous execution. User browser for a long time waiting for the execution of PHP script, that is, the user's browser status bar has been shown still in load.
Of course, there are other methods of similar principles, such as script tags and so on.
2.popen () function
Resource Popen (String command, string mode);
Opens a pipeline to a process that is generated by the derivation of a given command command. Opens a pipeline to a process that is generated by the derivation of a given command command.
So it can be invoked by calling it, but ignoring its output.
Pclose (Popen ("/home/xinchen/backend.php &", ' R '));
This method avoids the drawbacks of the first method and is also very quick. However, the problem is that this method cannot request another webservice through the HTTP protocol and can only execute local script files. And can only be opened one-way, unable to wear a large number of parameters to the invoked script.
And if the traffic is high, a lot of progress will be generated. If the use of external resources, but also to consider their own competition.
3.CURL Extension
Curl is a powerful HTTP command-line tool that simulates HTTP requests such as Post/get, and then gets and extracts the data, which is displayed on the "standard output" (stdout)
Copy Code code 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);

Use curl need to set Curopt_timeout to 1 (min 1, depressed). In other words, the client must wait at least 1 seconds.
4.fscokopen () function
Fsockopen is a very powerful function, support socket programming, you can use Fsockopen to implement the socket program such as mail, etc., use fcockopen need to manually stitching out the header part of the
Official documents: http://cn.php.net/fsockopen/
Copy Code code as follows:

$fp = Fsockopen ("www.example.com", $errno, $errstr, 30);
if (! $fp) {
echo "$errstr ($errno) <br/>\n";
} else {
$out = "get/backend.php/http/1.1\r\n";
$out. = "host:www.example.com\r\n";
$out. = "connection:close\r\n\r\n";
Fwrite ($fp, $out);
/* Ignore execution results
while (!feof ($fp)) {
Echo fgets ($FP, 128);
}*/
Fclose ($FP);
}

PHP calls the socket asynchronously
Copy Code code as follows:

?
$host = "www.aaa.com";
$path = "/report.php?" Reportid=1 ";
$cookie = session_id ();
$fp = Fsockopen ($host, $errno, $errstr, 30);
if (! $fp) {
Print "$errstr ($errno) <br/>\n";
Exit
}
$out = "Get". $path. " Http/1.1\r\n ";
$out. = "Host:". $host. " \ r \ n ";
$out. = "connection:close\r\n";
$out. = "Cookie:". $cookie. " \r\n\r\n ";
Fwrite ($fp, $out); Write request to socket
You can also choose to get a response from the server side
/*while (!feof ($fp)) {
Echo fgets ($FP, 128);
}*/
If you do not wait for the server-side response to close the socket directly
Fclose ($FP);
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.