This article mainly introduces the php simple socket server client code instance. This article provides two versions of server ports, and describes the code problems and improvements, the client code for using this socket server is provided. if you need it, you can refer to this article to share 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
<? 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; // the port number of the server running on the Socket. The value ranges from 1 to 65535, provided that the port is not used. // Set the timeout time to never time out, make sure that PHP does 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, in addition to waiting for connection requests from the client, the server basically does nothing ***** // 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, this information can be obtained by The socket_read () function and assigned to the $ input variable $ input = socket_read ($ spawn, 1024) of PHP) 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 the data obtained from the client. // the following does not explain. if you do not know the size of the data, go to $ input = trim ($ input ); // process the client input and return the result. after the client sends the data information, the socket_write () function is used to output the information. $ output = strrev ($ input ). "\ n"; // reverse the string. here we only want to better distinguish two pieces of information socket_write ($ spawn, $ output, strlen ($ output )) or die ("cocould not write output \ n"); // close socketssocket_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.
The code is as follows:
Set_time_limit (0 );
Perform a simple test on the script in your command prompt:
The code is 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:
<? Php $ commonProtocol = getprotobyname ("tcp"); $ socket = socket_create (AF_INET, SOCK_STREAM, $ commonProtocol); socket_bind ($ socket, 'localhost', 1337 ); // socket_bind () bind 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 () accept a Socket connection printf ("Socket connected \ r \ n"); // Check t O 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 Received ed \ r \ n"); printf ("Buffer :". $ buffer. "\ r \ n");} socket_close ($ connection); // socket_close () disable 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:
<?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("NO DATA
"); break; }else{ // Do something with the data in the buffer echo("Buffer Data: " . $buffer . "
"); }}echo("Writing to Socket
");// Write some test data to our socketif(!socket_write($socket, "SOME DATA\r\n")){ echo("Write failed
");}// Read any response from the socket phpernote.comwhile($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)){ echo("Data sent was: SOME DATA
Response was:" . $buffer . "
");}echo("Done Reading from Socket
");
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.