A detailed description of socket communication in PHP

Source: Internet
Author: User
Sometimes our PHP program needs to communicate with other systems, such as a company's official website to provide product traceability information inquiries, in the back-end site needs and enterprise traceability system or ERP system communication, at this time need to PHP network programming, PHP provides a sockets extension, the official website address is:

http://nl3.php.net/manual/zh/intro.sockets.php

This extension gives us the ability to directly manipulate socket sockets via PHP so that we can communicate with other systems, using the socket to work above the transport layer of the OSI network model, using the services provided by TCP and UDP directly, so that it can be used as a client for other application-layer protocols. For example, analog HTTP client (browser), common SMTP, POP, FTP can be used to emulate it, it is more fun to use it and allow Telnet Server interaction, these protocols are application-layer protocol so it can be interactive, custom communication between the system needs to customize the protocol.

Here is an example of using PHP to develop a simple file receiving server, another PHP client program shows how to communicate with this server program, the code is as follows.

Server-side programs:

<?php/** * This program demonstrates PHP network programming: Socket communication requires PHP to open php_sockets extension * This is a simple server program, receive the client sent the file, save after closing * Communication protocol is: File size:: File extension:: Valid data * The communication end identifier is: "-end-" * execute in command line or browser, recommended command line * Author: Cloud Guest "roaming the world, as guest quartet" *//**** configuration ****///the native IP address and port $address = ' 127.0.0.1 ' to bind the listener; $port = 81;error_reporting (E_all);//Prevent timeout set_time_limit (0);//Turn on absolute swipe, disable buffering of content Ob_implicit_flush ();//Create Socket resource if ($sock = Socket_create (Af_inet, Sock_stream, sol_tcp)) = = = False) {echo "socket_create () Failed:reason:". Socket_strerror (Socket_last_error ()). "\ n";} Bind socket to Port if (Socket_bind ($sock, $address, $port) = = = False) {echo "Socket_bind () Failed:reason:". Socket_strerror (Socket_last_error ($sock)). "\ n";} Start listening port, parameter 5 means that 5 connection requests can be queued in the buffer//queued link request will be executed after the previous connection has been broken, the buffer queue number is five, after the link request will be ignored directly, the client display cannot link//Note this 5 does not mean that 5 links can be carried out concurrently, Instead, allow 5 follow-up links to enter the queued if (Socket_listen ($sock, 5) = = = False) {echo "Socket_listen () Failed:reason:". Socket_strerror (Socket_last_error ($sock)). "\ n";} do {///The program runs here to block, just like pausing execution, once a request enters, the function stops blocking and returns the link resource if ($client _sock = Socket_accePT ($sock)) = = = False) {echo "socket_accept () Failed:reason:". Socket_strerror (Socket_last_error ($sock)).        "\ n";    Break    } echo "[Client connect start]\n]; $data = ""; The data received $data _size = 1; The received data size $received _size = 0; The actual data received $ext _name = "txt"; The default file name extension//starts interacting with the client do {//run to that place to block, and once the content is stopped blocking state, return the content if (false = = = ($buf = Socket_read ($client _sock , 2048)) {echo "Socket_read () Failed:reason:". Socket_strerror (Socket_last_error ($client _sock)).            "\ n"; Break 2; Failure to read fails, 2 of this will cause the client to stop the link after the end of the simulation server} if ($data _size = = = 1) {//Accept the data for the first time, resolve the communication protocol $arr = Explode ("::"            , $buf, 3);            $data _size = (int) $arr [0];            $ext _name = $arr [1];            $data. = $arr [2];            $received _size + = strlen ($data);        Continue        } $data. = $buf;        $received _size + = strlen ($BUF); if ($data _size <= $received _size) {if ($data _size < $received_size) {$data = substr ($data, 0, $data _size); } echo "Received:". $received _size. "/" . "Total:".            $data _size; $talkback = "-end-";            Send end of communication sign Socket_write ($client _sock, $talkback, strlen ($talkback));            File_put_contents ("Servertest.". $ext _name, $data); Break 2; Close Server} echo $talkback = "Received:". $received _size.        "\ n";    Socket_write ($client _sock, $talkback, strlen ($talkback));    } while (true); Socket_close ($client _sock);} while (true); Socket_close ($sock);? >

Client program:

<?php/** * This program demonstrates PHP network programming: Socket communication requires PHP to open the php_sockets extension * This is a simple client program to send files to the server * Communication protocol is: File size:: File extension:: Valid data * The communication end identifier is: "-end-" * in the command line or browser execution can be, the recommended command line, you need to first open server-side * Author: Cloud Guest "roaming the world, as a guest quartet" *//**** configuration ****/$file = "Yunke.jpg"; File to be sent//server IP and port number $address = ' 127.0.0.1 '; $port = 81;error_reporting (E_all);//Prevent timeout set_time_limit (0);//Turn on absolute swipe, Do not buffer output ob_implicit_flush (TRUE);//Create Socket Resource if (($sock = Socket_create (Af_inet, sock_stream, sol_tcp) = = = = False) {echo "so Cket_create () Failed:reason: ". Socket_strerror (Socket_last_error ()).    "\ n"; Exit ();} Open the link to the remote host if (Socket_connect ($sock, $address, $port) = = = False) {echo "Socket_connect () Failed:reason:". Socket_strerror (Socket_last_error ($sock)).    "\ n"; Exit ();} Constructs a large data to be sent approximately 10mb/* $data = ""; for ($i = 1; $i <= 10000000; $i + +) {$data. = "Data:". $i;} $data = $data. $data. $data; */$data = file_get_contents ($file), $data _size = strlen ($data); $arr _temp = Explode ('. ', $file); $ext _name = End ($ ARR_TEMP); $sock _data = $data _size. "::" . $ext_name. "::" .    $data;//Send data to the remote host while (true) {$sock _data_size = strlen ($sock _data);    $send _size = Socket_write ($sock, $sock _data, $sock _data_size); if ($send _size = = = False) {echo "Send false:". Socket_strerror (Socket_last_error ($sock)).        "\ n";        Socket_close ($sock);        echo "[Client shutdown]\n];    Exit ();    } if ($send _size = = $sock _data_size) {break; } $sock _data = substr ($sock _data, $send _size);}  Reads the return data while (true) {if (false = = = ($out = Socket_read ($sock, 2048))) {echo "Socket_read () Failed:reason:". Socket_strerror (Socket_last_error ($sock)).        "\ n";    Break 1; } echo "Server:". $out.    "\ n";    if (substr ($out,-5) = = "-end-") {//Convention end Mark break; }}//closes the socket resource socket_close ($sock); echo "[Client Shutdown]\nsend data:.] Format ($data _size), function format ($byte = 0) {if ($byte > 1024x768 * 1024x768) {return ceil ($byte/(1024 * 1024)) .    "MB"; } elseif ($byte > 1024x768) {return ceil ($byte/1024).    "KB"; } else {return $byte.    "Byte"; }}


This example shows a TCP short link to the server to send a file, in the actual project communication module is not so simple, need to consider more questions

Like what:

Whether a long connection is required (a TCP link that transmits data multiple times back and forth), data validation prevents corruption, the size-to-end byte order problem between different systems, custom communication protocols, sticky packet problems, timeout processing, concurrent access, traffic control, TCP packet unpacking, and so on

If you want to learn more about PHP network programming the above mentioned above need to learn the system, recommend a look at the implementation of Workerman

It is a PHP written socket server framework to help solve the socket communication problem, use it to build a custom server, etc.
Workerman Official website address is: http://www.workerman.net/

The following is a sample program that provides two view server HTTP headers and browser headers:

The following example looks at the header information returned by the server, modifies the server address that needs to be viewed, and then accesses the script in the browser:

<?phperror_reporting (E_all);//Prevent timeout set_time_limit (0);//Turn on absolute swipe, do not buffer output ob_implicit_flush (true); $address = ' Www.qq.com '; To view the server $port=80;//create the socket resource if (($sock = Socket_create (Af_inet, sock_stream, sol_tcp) = = = False) {echo "Socket_create ( ) Failed:reason: ". Socket_strerror (Socket_last_error ()).    "\ n"; Exit ();} Open the link to the remote host if (Socket_connect ($sock, gethostbyname ($address), $port) = = = False) {echo "Socket_connect () Failed:reaso N: ". Socket_strerror (Socket_last_error ($sock)).    "\ n"; Exit ();}  Constructs the HTTP header $msg = "get/http/1.1 \ r \ n"; $msg. = "Host: {$address}\r\n"; $msg. = "connection:close\r\n\r\n"; Instructs the server to disconnect when it is finished, without having to wait for links to other resources//If there is no such line, the server will wait until we continue to send data until the timeout is closed//And we will not send again, this will let the following Socket_read function wait for a long time/ Send to remote host Socket_write ($sock, $msg, strlen ($msg)), $str = "", while ($out = @socket_read ($sock, 2048*4)) {$str. = $out;} $str =explode ("\r\n\r\n", $str), $str = $str [0];if ($STR) {echo "<pre>\r\n". $str. " \r\n</pre> ";} else{echo "Nothing";} Close Socket Resource Socket_close ($sock);

The following is an example of viewing the browser header, which makes it easy to view the session information sent by the browser
First make sure that you close port 80, then modify the host file of the machine, direct the URL you want to access to the native 127.0.0.1 address, start this script using the PHP command line mode, and then use the browser to access the set of directed URLs, the program will always open, if you want to close please use CTRL in the console +c key combination, the program is as follows:

<?phperror_reporting (E_all);//Prevent timeout set_time_limit (0);//Turn on absolute swipe, disable buffering of content Ob_implicit_flush (); $address = ' 127.0.0.1 ' ; $port = 80;//Create Socket resource if (($sock = Socket_create (Af_inet, sock_stream, sol_tcp) = = = = False) {echo "socket_create () fail Ed:reason: ". Socket_strerror (Socket_last_error ()). "\ n";} Bind socket to Port if (Socket_bind ($sock, $address, $port) = = = False) {echo "Socket_bind () Failed:reason:". Socket_strerror (Socket_last_error ($sock)). "\ n";} Start listening port, parameter 5 means that 5 connection requests can be queued in the buffer//queued link requests will be executed after the previous connection has been broken, the buffer queue number is five, after the link request will be displayed cannot link//Note this 5 does not mean that 5 links can be carried out concurrently, Instead, allow 5 follow-up links to enter the queued if (Socket_listen ($sock, 5) = = = False) {echo "Socket_listen () Failed:reason:". Socket_strerror (Socket_last_error ($sock)). "\ n";} do {///programs run to block here, just like pausing execution, once a request enters, the function stops blocking and returns the linked resource//can use the Socket_set_nonblock function to set the non-blocking mode if ($msgsock = Socket_acce PT ($sock)) = = = False) {echo "socket_accept () Failed:reason:". Socket_strerror (Socket_last_error ($sock)).        "\ n";    Break }//After the link succeeds, display the prompt in the console echo "[Client start '. Date ("Y-m-d h:i:s"). "]        \ n "; Do {//Run to place blocking, once content stops blocking state, return content if (false = = = ($buf = Socket_read ($msgsock, 2048*6)) {echo] Socket_read () Failed:reason: ". Socket_strerror (Socket_last_error ($msgsock)).            "\ n"; Break 2;        Failure to read fails, 2 of this will cause the client to stop the link after the end of the simulation server} $talkback = "http/1.1 ok\r\n\r\n"; $talkback. = Date ("y-m-d h:i:s"). " \nbrowser HTTP headers:\n\n ". $buf."        \ n ";        Display the content to the client Socket_write ($msgsock, $talkback, strlen ($talkback));        Display the content to the server console echo "$BUF \ n"; break;    Interrupts this link to the browser} while (true); Socket_close ($msgsock);} while (true); Socket_close ($sock);? >
Related Article

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.