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