PHP implementation of the socket server code _php tutorial

Source: Internet
Author: User
This article mainly introduces the PHP simple socket Server Client code example, this article gives two versions of the server port, the code of the problem and improvements are described, and the use of this socket server client code, the need for friends can refer to the next

This article shares a simple socket example, using PHP. Implements a TCP service that receives input strings, processes and returns this string to the client.

Generate a Socket server

<?php/* file name: socket_server.php*///set some basic variables $host= "127.0.0.1";//socket the IP address of the server that is running $port=1234;//socket the port of the server that is running, The port value is a number from 1 to 65535, provided that the port is not used//set the time-out, which is set to never time out, to ensure that PHP does not time out while waiting for the client to connect. Set_time_limit (0);//Create a socket that returns a socket handle $socket=socket_create (af_inet,sock_stream,0) or Die ("Could not create Socket\n ");//bind 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, In addition to waiting for a connection request from the client, the server basically does nothing ******///another socket to handle the service-side communication with the client $spawn=socket_accept ($socket) or Die ("Could not accept Incoming connection\n ");//Read client input, when a connection is established, the server will wait for the client to send some input information, which can be obtained by the Socket_read () function, and assign it to PHP $input variable $ Input=socket_read ($spawn, 1024x768) or Die ("Could not read input\n"); the second parameter of//socker_read is used to specify the number of bytes read, which you can use to limit the size of the data fetched from the client/ /below this does not explain, do not know oneself wall go to $input=trim ($input);//process the client input and return the result, when the client sends the data information, the information output depends on the Socket_write () function to complete $output=strrev ($ Input). " \ n ";//reverse string, here is just to better distinguish between two messages Socket_write ($Spawn, $output, strlen ($output)) or Die ("Could 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 because there will be a server, not a Web page. If you try to run the script using a Web browser, it is likely 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 run it using the command prompt.

The code is as follows:

Set_time_limit (0);


Make a simple test of the script at your command prompt:

The code is as follows:

Php.exe socket_server.php


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

The server side above has three questions:

1. It cannot accept multiple connections.

2. It only completes a single command.

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

This first problem is easier to solve, you can use an application to connect to the server every time. But the problem behind it is that you need to use a Web page to connect to the server, which is a bit more difficult. You can let 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.

To build on the previous code, generate 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 in on this socket $connection = socket_accept ($socket);//socket_accept () accepts a socket connection printf ("Socket connected\r\ n "); Check to see if there was anything in the buffer if ($buffer! = "") {printf ("Something is 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, 1024x768, php_normal_re AD) {//socket_read () reads data of a specified length $buffer = $data; Socket_write ($connection, "Information received\r\n"); printf ("Buffer: " . $buffer. "\ r \ n"); } socket_close ($connection); Socket_close () Close a socket resource printf ("Closed the Socket\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 a connection is generated it will print "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 receiving information of the data, and once it accepts the information, it saves the information to the data and lets the connected computer know the information and finally closes the connection. When the connection is closed, the server starts processing the next connection.

Generate a Socket client

It's easy to deal with a second problem. 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 and you are able to send your data to the server. On another client connection, it will process those data.

The following example demonstrates the use of a socket:

<?php//Create the socket and Connect$socket = Socket_create (Af_inet, Sock_stream, sol_tcp); $connection = Socket_conne CT ($socket, ' localhost ', 1337), while ($buffer = Socket_read ($socket, 1024x768, php_normal_read)) {if ($buffer = = "NO DATA") {EC Ho ("<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 Socketif (!socket_write ($socket, "some data\ r\n ")) {echo (" <p>write failed</p> ");} Read any response from the socket phpernote.comwhile ($buffer = Socket_read ($socket, 1024x768, 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 shows the client connecting 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 accepted, it writes 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.