PHP Simple Socket Server client code instance _php tips

Source: Internet
Author: User

This article shares a simple example of a socket, using PHP. Implements a receive input string that handles and returns this string to the client's TCP service.

Generate a socket service side

<?php/* FileName: socket_server.php*///Set some basic variables $host = "127.0.0.1";//socket the IP address of the server running $port =1234;//socket the port of the server running.
The port takes a number between 1 and 65535, provided that the port is not used/set timeout, set to never timeout, and ensure that PHP does not time out while waiting for the client to connect.
Set_time_limit (0);
Creates a socket that returns a socket handle $socket =socket_create (af_inet,sock_stream,0) or die ("could not create socket\n");
Bind the socket to the specified address and port $result =socket_bind ($socket, $host, $port) or die ("could not bind to socket\n");
Start listening for external connections $result =socket_listen ($socket, 3) or die ("could not set up socket listener\n"); /****** here, the server basically does nothing but wait for a connection request from the client ******///Another socket to handle the communication between the client and the service $spawn =socket_accept ($socket) or Die ("could
Not accept incoming connection\n "); Reading the input from the client, 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 assigned to the PHP $input variable $input =socket_read ($spawn,
1024) or die ("could not read input\n");
The second parameter of Socker_read specifies the number of bytes to read, which you can use to limit the size of the data fetched from the client//below this does not explain, do not know the wall to $input =trim ($input); Processing the client input and returning the result, when the client sends the data information, the output of the information depends on the Socket_write () function to complete the $output =strrev ($input). \ n ";//reverse string, here just toBetter distinguish between two information socket_write ($spawn, $output, strlen ($output)) or die ("could not write output\n");
Closure of sockets Socket_close ($spawn); Socket_close ($socket);

Hint: You should use your command prompt to run the above code. The reason is that this will produce a server instead of a Web page. If you try to run the script using a Web browser, chances are that it will exceed the 30-second limit. You can use the following code to set an unlimited run time, but it is recommended that you use a command prompt to run.

Copy Code code as follows:

Set_time_limit (0);

Do a simple test of this script at your command prompt:
Copy Code code as follows:

Php.exe socket_server.php

If you do not set the path of the PHP interpreter in the system's environment variables, you will need to specify a detailed path to the Php.exe. When you run this server side, you can connect to the port 1337来 by remote login (telnet) to test the server.

There are three problems with the server side above:

1. It cannot accept multiple connections.

2. It completes only one command.

3. You cannot connect to this server through a Web browser.

This first problem is easier to solve and you can use an application to connect to the server each time. But the problem is that you need to use a Web page to connect to the server, which is more difficult. You can have your server accept the connection, and then some data to the client (if it must be written), close the connection and wait for the next connection.

The

is modified on the basis of the previous code, producing the following code to do your new server side:

<?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 the this socket $connection = socket_accept ($socket);//socket_accept ()
 Accept a socket connection printf ("Socket connected\r\n"); Check to the If there are anything in the buffer if ($buffer!= "") {printf ("Something are in the buffer...sending data.") ..
 \ r \ n "); Socket_write ($connection, $buffer. "\ r \ n");
 Socket_write () writes 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 the data of the specified length $buffer = $
 Data
 Socket_write ($connection, "Information received\r\n"); printf ("Buffer:"). $buffer.
 "\ r \ n"); } socket_close ($connection); Socket_close () closes a socket resource printf ("Closed theSocket\r\n\r\n ");
 }


What does this server side do? It initializes a socket and opens a cache to send and receive data. It waits for a connection, and once it produces a connection, it prints "Socket connected" on the server-side screen. This server checks the buffer, and if there is data in the buffer, it sends the data to the connected computer. It then sends the acceptance information for this data, and once it accepts the information, it saves the information to the data and lets the connected computer know the information, and then closes the connection. When the connection is closed, the server starts processing the next connection again.

Generate a Socket client

It is easy to deal with the second question. You need to generate a PHP page to connect a socket, send some data into it's cache and process it. Then you have a processed data in the Dayton, you can send your data to the server. On a different client connection, it will process those data.

The following example demonstrates the use of sockets:

 <?php//Create the socket and connect $socket = Socket_create (Af_inet, Sock_stream, S
OL_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&G
 t; ");
 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 for this example demonstrates that the client connects to the server. The client reads the data. If this is the first time a connection is reached for this loop, the server will send "NO DATA" back to the client. If this happens, the client is on top of the connection. The client sends its data to the server, the data is sent to the server, and the client waits for a response. Once the response is received, it will write the response to the screen.

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.