How to implement _php technique of socket server with PHP

Source: Internet
Author: User
Tags set time

The socket server works in such a way that it runs uninterrupted to wait for the client to connect. Once the client is connected, the server adds it to the customer list and then starts waiting for the message 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'll listen on $address = ' localhost '; 
$port = 10000; 
 
$max _clients = 10; 
 
Array that would hold client information $client = array (); 
Create a TCP Stream socket $sock = socket_create (af_inet, sock_stream, 0); 
Bind the socket to a 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 are 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_re 
  AD ($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 ']) &&am P 
    $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);

Gee, at first glance this seems like a big project, but we can break it down into smaller pieces first.

The first part is creating the server. Lines:2 to 20.

This section of code sets the variable, address, port, maximum client, and client arrays. Next, create the socket and bind it to the address and port that we specify.

The next thing we're going to do is execute a dead loop (actually we did it on purpose!). )。 Lines:22 to 32.

The first step in this part of the code is to set the $read array. This array contains sockets for all clients and sockets for our home server. This variable is later used for the SELECT statement: tells PHP to listen for every message from these clients.

The last argument to Socket_select () tells us that the server waits up to 5 seconds before returning a value. If its return value is less than 1, it means that no data is received, so just return to the top of the loop and wait.

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

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

the code block to be described below is quite large and is a major part of the server. when a client sends a message to the server, it needs the code to come forward and handle it. Messages can be various, disconnect messages, and actually disconnect-as long as the server needs to process messages. lines:46 to the end.

The code loops through each client and checks to see if messages from them are received. If it is, get the input content. Check if this is a disconnected message based on the input, and if so, remove them from the array, otherwise it is a normal message, and then our server passes all the clients again, and one by one writes the message to them and skips the sender.

OK, 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.