PHP asynchronous socket call implementation code _ PHP Tutorial

Source: Internet
Author: User
Tags email account
PHP asynchronously calls the socket implementation code. PHP Asynchronous call implementation: communication between the browser and the server is oriented to the connectionless HTTP protocol. connectionless programs are characterized by client requests to the server and server. PHP Asynchronous call implementation method
The browser and server communicate with each other over the connectionless HTTP protocol. connectionless programs are characterized by client requests to the server. the server outputs the corresponding program according to the request, persistent connections cannot be maintained.
In this case, a problem occurs. the corresponding server of a client may execute for 1 second or 1 minute, so that the browser will remain in the waiting state. if the program runs slowly, the user may be impatient to close the browser.
Sometimes, we do not need to care about the results of program execution, and there is no need to waste time and patience, so we have to figure out a way for the program to wait for silent execution in the background.
For example, in the current scenario, a recommendation email is sent to 1000 users. the user enters or imports the email account and submits it to the server for sending.

The code is as follows:


$ Count = count ($ emailarr );
For ($ I = 0; $ I <$ count; $ I ++)
{
Sendmail (...); // send an email
}
?>


The user experience of this code is very poor and cannot be used in practice. first, sending so many emails will result in server operation timeout. In fact, a long waiting time will cause the user to doubt and lose confidence in the system products. However, you do not need to wait until all the 1000 emails are sent before submitting the email successfully. you can submit the email to the backend and then send the message to the user.
At this time, we need the "asynchronous execution" technology to execute code. asynchronous execution is characterized by silent execution in the background, and users do not have to wait for the code execution results. The advantages of asynchronous execution are as follows:
1. get rid of the application's dependency on a single task
2. improved program execution efficiency
3. improved program scalability
4. improved user experience in certain scenarios
5. because PHP does not support multithreading, the Asynchronous call of multiple HTTP requests achieves parallel execution of the program. However, if there are too many HTTP requests, the system overhead will be greatly increased.
Common PHP asynchronous execution methods:
1. client pages use AJAX technology to request servers
1. the simplest method is to embed an AJAX call in the HTML code returned to the client, or embed an 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.
However, the disadvantage is that Ajax should be triggered after onLoad. that is to say, when the user clicks the page and closes it, the background script will not be triggered.
Using the img label cannot be called a strictly asynchronous execution. The user's browser will wait for a long time until the php script is executed, that is, the status bar of the user's browser is still being loaded.
Of course, you can also use other similar methods, such as script labels.
2. popen () function
Resource popen (string command, string mode );
// Open an Pipeline pointing to a process. this process is generated by the execution of the derived command. Open an Pipeline pointing to a process, which is generated by running the command derived from a process.
Therefore, you can call it, but ignore its output.
Pclose (popen ("/home/xinchen/backend. php &", 'r '));
This method avoids the disadvantages of the first method and is also very fast. However, the problem is that this method cannot request another WebService through the HTTP protocol and can only execute local script files. In addition, it can only be opened in one way, and a large number of parameters cannot be used to call scripts.
In addition, if the traffic is high, a large number of processes will be generated. If external resources are used, you must consider competition on your own.
3. CURL extension
CURL is a powerful HTTP command line tool that can simulate POST/GET and other HTTP requests and then obtain and extract data, which is displayed on stdout.

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 );


To use CURL, set CUROPT_TIMEOUT to 1 (minimum: 1, depressing ). That is to say, 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. to use fcockopen, you need to manually splice the header part.
Official documents: http://cn.php.net/fsockopen/

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.1 \ r \ n ";
$ Out. = "Host: www.example.com \ r \ n ";
$ Out. = "Connection: Close \ r \ n ";
Fwrite ($ fp, $ out );
/* Ignore execution results
While (! Feof ($ fp )){
Echo fgets ($ fp, 128 );
}*/
Fclose ($ fp );
}


PHP asynchronously calls socket

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.1 \ r \ n ";
$ Out. = "Host:". $ host. "\ r \ n ";
$ Out. = "Connection: Close \ r \ n ";
$ Out. = "Cookie:". $ cookie. "\ r \ n ";
Fwrite ($ fp, $ out); // write requests to the socket
// You can also choose to obtain the server response
/* While (! Feof ($ fp )){
Echo fgets ($ fp, 128 );
}*/
// Close the socket directly without waiting for the response from the server.
Fclose ($ fp );
?>

The middleware browser and server communicate with each other over the connectionless HTTP protocol. connectionless programs are characterized by client requests to the server, server...

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.