Php simple socket server client code example
This article shares a simple socket example using php. Implement a TCP Service that receives the input string, processes and returns the string to the client.
Generate a socket server
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<? Php /* File name: socket_server.php */ // Set some basic variables $ Host = "127.0.0.1"; // ip address of the server running the Socket $ Port = 1234; // port of the server running the Socket. The port value ranges from 1 to 65535, provided that the port is not used. // Set the timeout time. Here, it is set to never time out, so that PHP will not time out while waiting for client connection. Set_time_limit (0 ); // Create a Socket and return a Socket handle $ Socket = socket_create (AF_INET, SOCK_STREAM, 0) or die ("cocould not create socket \ n "); // Bind the Socket to the specified address and port $ Result = socket_bind ($ socket, $ host, $ port) or die ("cocould not bind to socket \ n "); // Start listening for external connections $ Result = socket_listen ($ socket, 3) or die ("cocould not set up socket listener \ n "); /***** Here, the server basically does nothing except waiting for connection requests from the client ******/ // Another Socket to process the communication between the server and the client $ Spawn = socket_accept ($ socket) or die ("cocould not accept incoming connection \ n "); // Read client input. When a connection is established, the server waits for the client to send some input information, which can be obtained by the socket_read () function, and assign it to the $ input variable of PHP. $ Input = socket_read ($ spawn, 1024) or die ("cocould not read input \ n "); // The second parameter of socker_read is used to specify the number of bytes to read. You can use it to limit the size of data obtained from the client. // This is not an explanation. If you do not know what to do $ Input = trim ($ input ); // Process the input from the client and return the result. After the client sends the data, the socket_write () function is used to output the information. $ Output = strrev ($ input). "\ n"; // reverse the string to better distinguish the two messages. Socket_write ($ spawn, $ output, strlen ($ output) or die ("cocould not write output \ n "); // Disable sockets Socket_close ($ spawn ); Socket_close ($ socket ); |
Tip: you should use your command prompt to run the above Code. The reason is that a server is generated, not a Web page. If you try to use a Web browser to run this script, it is likely to exceed 30 seconds. You can use the following code to set an unlimited running time, but we recommend that you use a command prompt to run it.
Copy the Code as follows:
Set_time_limit (0 );
Perform a simple test on the script in your command prompt:
Copy the Code as follows:
Php.exe socket_server.php
If you have not set the PHP interpreter in the system environment variable, you can specify the detailed path for php.exe. When you run this server, you can connect to port 1337 through remote login (telnet) to test this server.
The preceding server has three problems:
1. It cannot accept multiple connections.
2. It only completes a unique command.
3. You cannot connect to this server through a Web browser.
This first problem is easy to solve. You can use an application to connect to the server every time. However, the problem is that you need to use a Web page to connect to the server, which is more difficult. You can make your server accept the connection and then send some data to the client (if it must be written), close the connection and wait for the next connection.
Make improvements based on the previous Code and generate the following code for your new server:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<? Php $ CommonProtocol = getprotobyname ("tcp "); $ Socket = socket_create (AF_INET, SOCK_STREAM, $ commonProtocol ); Socket_bind ($ socket, 'localhost', 1337); // socket_bind () binds the socket to an IP address and port. Socket_listen ($ socket ); $ Buffer = "no data "; While (true ){ // Accept any connections coming in on this socket $ Connection = socket_accept ($ socket); // socket_accept () accepts a Socket connection Printf ("Socket connected \ r \ n "); // Check to see if there is anything in the buffer If ($ buffer! = ""){ Printf ("Something is in the buffer... sending data... \ r \ n "); Socket_write ($ connection, $ buffer. "\ r \ n"); // socket_write () write data to the socket Cache Printf ("Wrote to socket \ r \ n "); } Else { Printf ("No Data in the buffer \ r \ n "); } // Get the input While ($ data = socket_read ($ connection, 1024, PHP_NORMAL_READ) {// socket_read () reads data of the specified length $ Buffer = $ data; Socket_write ($ connection, "Information stored ed \ r \ n "); Printf ("Buffer:". $ buffer. "\ r \ n "); } Socket_close ($ connection); // socket_close () close a socket Resource Printf ("Closed the socket \ r \ n "); } |
What does this server do? It initializes a socket and opens a cache to send and receive data. It waits for a connection. Once a connection is generated, it prints "Socket connected" on the server screen. This server checks the buffer zone. If there is data in the buffer zone, it sends the data to the connected computer. Then, it sends the receiving information of the Data. Once it accepts the information, it stores the information in the data, allows the connected computer to know the information, and closes the connection. When the connection is closed, the server starts to process the next connection.
Generate a socket Client
It is easy to handle the second problem. You need to generate a php page to connect to a socket, send some data to its cache, and process it. Then you have a processed data record, and you can send your data to the server. Connect to another client and it will process the data.
The following example demonstrates the use of socket:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<? Php // Create the socket and connect $ Socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP ); $ Connection = socket_connect ($ socket, 'localhost', 1337 ); While ($ buffer = socket_read ($ socket, 1024, PHP_NORMAL_READ )){ If ($ buffer = "no data "){ Echo ("<p> no data </p> "); Break; } Else { // Do something with the data in the buffer Echo ("<p> Buffer Data:". $ buffer. "</p> "); } } Echo ("<p> Writing to Socket </p> "); // Write some test data to our socket If (! Socket_write ($ socket, "some data \ r \ n ")){ Echo ("<p> Write failed </p> "); } // Read any response from the socket phpernote.com While ($ buffer = socket_read ($ socket, 1024, PHP_NORMAL_READ )){ Echo ("<p> Data sent was: some data <br> Response was:". $ buffer. "</p> "); } Echo ("<p> Done Reading from Socket </p> "); |
The code in this example demonstrates how to connect the client to the server. The client reads data. If this is the first connection to reach this loop, the server will send "no data" to the client. If this happens, the client is connected. The client sends its data to the server, and the data is sent to the server. The client waits for a response. Once a response is received, it writes the response to the screen.