How to implement Socket server using PHP

Source: Internet
Author: User
Do you want to build chat applications or even games? Then, the socket server will be your first step. Once you understand the basic functions of creating a server, the subsequent optimization steps will become equally simple. if you need a friend, you can refer to the working method of the socket server as follows, run continuously to wait for the client connection. Once the client is connected, the server adds it to the customer list and waits for messages from the client.

Do not go away. The following is the complete source code:

// Set time limit to indefinite execution set_time_limit (0);  // Set the ip and port we will listen on $address = 'localhost'; $port = 10000; $max_clients = 10;  // Array that will hold client information $client = Array();  // Create a TCP Stream socket $sock = socket_create(AF_INET, SOCK_STREAM, 0); // Bind the socket to an address/port socket_bind($sock, $address, $port) or die('Could not bind to address'); // Start listening for connections socket_listen($sock);  echo "Waiting for connections...\r\n";  // Loop continuously while (true) { // Setup clients listen socket for reading $read[0] = $sock; for ($i = 0; $i < $max_clients; $i++) {  if (isset($client[$i]['sock']))   $read[$i + 1] = $client[$i]['sock']; } // Set up a blocking call to socket_select() if (socket_select($read, $write = NULL, $except = NULL, $tv_sec = 5) < 1)  continue; /* if a new connection is being made add it to the client array */ if (in_array($sock, $read)) {  for ($i = 0; $i < $max_clients; $i++) {   if (empty($client[$i]['sock'])) {   $client[$i]['sock'] = socket_accept($sock);   echo "New client connected $i\r\n";   break;   }   elseif ($i == $max_clients - 1)   echo "Too many clients...\r\n";  } } // end if in_array  // If a client is trying to write - handle it now for ($i = 0; $i < $max_clients; $i++) { // for each client  if (isset($client[$i]['sock'])) {   if (in_array($client[$i]['sock'], $read)) {   $input = socket_read($client[$i]['sock'], 1024);   if ($input == null) {    echo "Client disconnecting $i\r\n";    // Zero length string meaning disconnected    unset($client[$i]);   } else {    echo "New input received $i\r\n";    // send it to the other clients    for ($j = 0; $j < $max_clients; $j++) {    if (isset($client[$j]['sock']) && $j != $i) {     echo "Writing '$input' to client $j\r\n";     socket_write($client[$j]['sock'], $input, strlen($input));    }    }    if ($input == 'exit') {    // requested disconnect    socket_close($client[$i]['sock']);    }   }   } else {   echo "Client disconnected $i\r\n";   // Close the socket   socket_close($client[$i]['sock']);   unset($client[$i]);   }  } } } // end while // Close the master sockets socket_close($sock); 

It seems like a big project at first glance, but we can break it down into several smaller parts first.

The first part is to create a server. Lines: 2 to 20.

The code sets the variables, addresses, ports, maximum clients, and client arrays. Next, create a socket and bind it to the specified address and port.

What we need to do below is to execute an endless loop (we actually did it !). Lines: 22 to 32.

In this part of the code, the first step is to set the $ read array. These groups contain sockets of all clients and the sockets of our master server. This variable will be used later in the select statement to tell PHP to listen to each message from these clients.

The last parameter of socket_select () tells us that the server can wait up to five seconds before the return value. If the returned value is less than 1, it indicates that no data is received. Therefore, you only need to return to the top of the loop and continue waiting.

The next part of the script is to add a new client to the array. Lines: 33 to 44.

Place the new client at the end of the list. Check to make sure that the number of clients does not exceed the number that we want the server to process.

The code block to be introduced below is quite large and is also the main part of the server.When the client sends messages to the server, this code is required to handle them. Messages can be various. Disconnect messages and actually disconnect messages as long as they are messages that the server needs to process.Lines: 46 to the end.

Code loops through each client and checks whether messages from them are received. If yes, obtain the input content. Check whether this is a disconnected message based on input. If yes, delete them from the array. Otherwise, it is a normal message. then our server passes all the clients again, and write information to them one by one, skipping the sender.

Now, let's try to create your own chat server!

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.