Phpsocket client and server communication instance-PHP source code

Source: Internet
Author: User
I will not introduce what phpsocket is. Below I will give you some examples of communication between the client and the server implemented by phpsocket. I will not introduce anything about php socket. The following describes some examples of communication between the client and the server implemented by php socket.

Script ec (2); script

Server

The Code is as follows:

Set_time_limit (0 );
$ Host = "localhost ";
$ Port = 1001;

// Create a connection
$ Socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die ("cannot create socketn ");
// Bind the socket to the port
$ Result = socket_bind ($ socket, $ host, $ port) or die ("cannot bind port to socketn ");
// Start listening to this port
$ Result = socket_listen ($ socket, 4) or die ("cocould not set up socket listenn ");
// Accept the connection and use another socket to process the communication
$ Msgsock = socket_accept ($ socket) or die ("cannot accept incoming connectionn ");
If ($ msgsock ){
Echo date ("Y-m-d H: I: s D ");
}
// Read the information sent from the client
$ Input = socket_read ($ msgsock, 1024) or die ("cannot read inputn ");
$ Input = trim ($ input );
$ Output = strrev ($ input). "Reverse Order n ";
// Process the received information and return it to the client
Socket_write ($ msgsock, $ output, strlen ($ output) or die ("cannot write ");
// Close the socket connection
Socket_close ($ msgsock );
Socket_close ($ socket );

?>

Client

The Code is as follows:

Set_time_limit (0 );
$ Host = "localhost ";
$ Port = 1001;

// Create a socket
$ Socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die ("cannot create socketn ");

$ Conn = socket_connect ($ socket, $ host, $ port) or die ("cannot connect servern ");

If ($ conn) {echo "client connect OK! ";}

Socket_write ($ socket, "hello world! ") Or die (" cannot write datan ");

$ Buffer = fig ($ socket, 1024, PHP_NORMAL_READ );

If ($ buffer ){
Echo "response was:". $ buffer. "n ";
}
Socket_close ($ socket );
?>

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.