PHP socket communication 3: server-side instances

Source: Internet
Author: User
In the first two articles, we have introduced two protocols for socket communication: TCP and UDP. Next, we will start from this article to learn how to write a small program to implement socket communication. in the first two articles, we have introduced the two protocols that socket communication relies on: TCP and UDP protocols. From this article, we will learn how to write a small program that implements socket communication.
This program is divided into two php files. on the server side, we become s. php, and on the client side, we become c. php. The specific implementation result is that the client uses socket communication to send data to the server, and the server prints the data received through socket communication.
In this article, we will explain the code of s. php in detail: ";} Else {echo" socket creation failed!
";}// Link to the server and return the boolean value if ($ res = socket_connect ($ socket, $ _ server, $ port) {echo" the server connection is successful.
";} Else {echo" server connection failed
";}// Set the message sent to the server $ info =" Hello world! "; // Use socket_write () to transmit data to the server. if it fails, the function returns a negative value if ($ res = socket_write ($ socket, $ info, strlen ($ info) <0) {echo "failed to transmit data
";}Else {echo" data transferred successfully "; // receives the data transmitted by the server $ sinfo = socket_read ($ socket, 1024); if ($ sinfo) {echo "server data accepted successfully"; var_dump ($ sinfo) ;}else {echo "server data accepted failed" ;}}?> Note that the socket communication requires the server to continuously listen to the port for any client connection requests, so it cannot be accessed through a browser. The command line should be used to run the file with php.exe. If you have any questions, you can refer to how to use php.exe to run the php file.

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.