2012-11-03 25 views
11

मैं एक साधारण क्लाइंट/सर्वर एप्लिकेशन बनाने की कोशिश कर रहा हूं और इस प्रकार मैं PHP में सॉकेट के साथ प्रयोग कर रहा हूं।PHP सॉकेट्स - एकाधिक कनेक्शन स्वीकार करें

अब मेरे पास सी # में एक साधारण क्लाइंट है जो सर्वर से अच्छी तरह से कनेक्ट होता है, लेकिन मैं केवल एक ही क्लाइंट को इस सर्वर से कनेक्ट कर सकता हूं (मुझे यह कोड नमूना ऑनलाइन मिला और परीक्षण उद्देश्यों के लिए थोड़ा सा tweaked)।

अजीब पर्याप्त मैं एक ही उदाहरण यहां के आधार पर एक ही सवाल पाया,: https://stackoverflow.com/questions/10318023/php-socket-connections-cant-handle-multiple-connection

मैं इसके बारे में हर हिस्से समझने की कोशिश की और मैं इसे कैसे विस्तार से काम करता है को देखने के लिए करीब हूँ, लेकिन किसी कारण से, जब मैं दूसरे क्लाइंट को कनेक्ट करता हूं, तो पहला डिस्कनेक्ट/क्रैश हो जाता है।

क्या कोई मुझे कुछ जंगली विचार या पॉइंटर दे सकता है जहां मुझे देखना चाहिए?

<?php 
// Set time limit to indefinite execution 
set_time_limit (0); 
// Set the ip and port we will listen on 
$address = '127.0.0.1'; 
$port = 9000; 
$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); 
// Loop continuously 
while (true) { 
    // Setup clients listen socket for reading 
    $read[0] = $sock; 
    for ($i = 0; $i < $max_clients; $i++) 
    { 
     if (isset($client[$i])) 
     if ($client[$i]['sock'] != null) 
      $read[$i + 1] = $client[$i]['sock'] ; 
    } 
    // Set up a blocking call to socket_select() 
    $ready = socket_select($read, $write = NULL, $except = NULL, $tv_sec = NULL); 
    /* 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 (!isset($client[$i])) { 
       $client[$i] = array(); 
       $client[$i]['sock'] = socket_accept($sock); 
       echo("Accepting incomming connection...\n"); 
       break; 
      } 
      elseif ($i == $max_clients - 1) 
       print ("too many clients"); 
     } 
     if (--$ready <= 0) 
      continue; 
    } // 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])) 
     if (in_array($client[$i]['sock'] , $read)) 
     { 
      $input = socket_read($client[$i]['sock'] , 1024); 
      if ($input == null) { 
       // Zero length string meaning disconnected 
       echo("Client disconnected\n"); 
       unset($client[$i]); 
      } 
      $n = trim($input); 
      if ($n == 'exit') { 
       echo("Client requested disconnect\n"); 
       // requested disconnect 
       socket_close($client[$i]['sock']); 
      } 
      if(substr($n,0,3) == 'say') { 
       //broadcast 
       echo("Broadcast received\n"); 
       for ($j = 0; $j < $max_clients; $j++) // for each client 
       { 
        if (isset($client[$j])) 
        if ($client[$j]['sock']) { 
         socket_write($client[$j]['sock'], substr($n, 4, strlen($n)-4).chr(0)); 
        } 
       } 
      } elseif ($input) { 
       echo("Returning stripped input\n"); 
       // strip white spaces and write back to user 
       $output = ereg_replace("[ \t\n\r]","",$input).chr(0); 
       socket_write($client[$i]['sock'],$output); 
      } 
     } else { 
      // Close the socket 
      if (isset($client[$i])) 
      echo("Client disconnected\n"); 
      if ($client[$i]['sock'] != null){ 
       socket_close($client[$i]['sock']); 
       unset($client[$i]); 
      } 
     } 
    } 
} // end while 
// Close the master sockets 
echo("Shutting down\n"); 
socket_close($sock); 
?> 
+0

क्या आपके पास कभी इसके साथ कोई भाग्य है? –

+0

देखें: [सॉकेटसेवर.क्लास.एफ़पी] (https://gist.github.com/navarr/459321) – kenorb

उत्तर

1

आमतौर पर सॉकेट सर्वर को बहु-थ्रेडेड होने की आवश्यकता होती है यदि आप> 1 क्लाइंट को संभालना चाहते हैं। आप प्रत्येक ग्राहक अनुरोध के लिए 'सुनें' धागा बनायेंगे और एक नया 'उत्तर' धागा तैयार करेंगे। मुझे यकीन नहीं है कि PHP इस तरह की स्थिति को कैसे संभालेगा। शायद यह एक कांटा तंत्र है?

संपादित करें: ऐसा नहीं लगता है कि PHP प्रति से थ्रेडिंग प्रदान करता है (http://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-plplications) यदि आप चाहते हैं सॉकेट सर्वर के लिए सामान्य प्रतिमान का पालन करने के लिए आप बच्चे के अनुरोध को संभालने के लिए प्रक्रिया को बढ़ाने के लिए 'पॉपन' का उपयोग कर दूर हो सकते हैं। सॉकेट आईडी को बंद करें और जब बच्चे सॉकेट बंद हो जाए तो इसे बंद कर दें। यदि आपकी सर्वर प्रक्रिया बंद हो जाती है तो आपको इन प्रक्रियाओं को अनाथ करने से बचने के लिए इस सूची के शीर्ष पर रखना होगा।

FWIW: यहां बहु-क्लाइंट सर्वर के कुछ उदाहरण हैं: http://php.net/manual/en/function.socket-accept.php

+0

अरे, आपके उत्तर के लिए धन्यवाद। क्या आपने वास्तव में अपना कोड पढ़ा था? मैं उन सभी को संभालने के लिए कनेक्शन की एक सरणी चल रहा हूं। आपके द्वारा लिंक किए गए कई उदाहरणों की तरह ही। अभी भी धन्यवाद! :) – JapyDooge

+0

सही - लेकिन ऐसा लगता है कि आप कनेक्ट और पढ़ने दोनों पर अवरुद्ध कर रहे हैं। जब तक कोई नया कनेक्शन नहीं बनाया जाता है तब तक यह किसी भी लंबित अनुरोध की सेवा नहीं करेगा। – ethrbunny

+0

आह जो मामला हो सकता है, इसके लिए धन्यवाद :) मैं यह देखने जा रहा हूं कि मैं इसे कैसे प्राप्त कर सकता हूं! – JapyDooge

1

यह स्क्रिप्ट मुझे

के लिए पूरी तरह से काम कर रहा है
<?php 
    /*! @class  SocketServer 
     @author  Navarr Barnier 
     @abstract A Framework for creating a multi-client server using the PHP language. 
    */ 
    class SocketServer 
    { 
     /*! @var  config 
      @abstract Array - an array of configuration information used by the server. 
     */ 
     protected $config; 

     /*! @var  hooks 
      @abstract Array - a dictionary of hooks and the callbacks attached to them. 
     */ 
     protected $hooks; 

     /*! @var  master_socket 
      @abstract resource - The master socket used by the server. 
     */ 
     protected $master_socket; 

     /*! @var  max_clients 
      @abstract unsigned int - The maximum number of clients allowed to connect. 
     */ 
     public $max_clients = 10; 

     /*! @var  max_read 
      @abstract unsigned int - The maximum number of bytes to read from a socket at a single time. 
     */ 
     public $max_read = 1024; 

     /*! @var  clients 
      @abstract Array - an array of connected clients. 
     */ 
     public $clients; 

     /*! @function __construct 
      @abstract Creates the socket and starts listening to it. 
      @param  string - IP Address to bind to, NULL for default. 
      @param  int - Port to bind to 
      @result  void 
     */ 
     public function __construct($bind_ip,$port) 
     { 
      set_time_limit(0); 
      $this->hooks = array(); 

      $this->config["ip"] = $bind_ip; 
      $this->config["port"] = $port; 

      $this->master_socket = socket_create(AF_INET, SOCK_STREAM, 0); 
      socket_bind($this->master_socket,$this->config["ip"],$this->config["port"]) or die("Issue Binding"); 
      socket_getsockname($this->master_socket,$bind_ip,$port); 
      socket_listen($this->master_socket); 
      SocketServer::debug("Listenting for connections on {$bind_ip}:{$port}"); 
     } 

     /*! @function hook 
      @abstract Adds a function to be called whenever a certain action happens. Can be extended in your implementation. 
      @param  string - Command 
      @param  callback- Function to Call. 
      @see  unhook 
      @see  trigger_hooks 
      @result  void 
     */ 
     public function hook($command,$function) 
     { 
      $command = strtoupper($command); 
      if(!isset($this->hooks[$command])) { $this->hooks[$command] = array(); } 
      $k = array_search($function,$this->hooks[$command]); 
      if($k === FALSE) 
      { 
       $this->hooks[$command][] = $function; 
      } 
     } 

     /*! @function unhook 
      @abstract Deletes a function from the call list for a certain action. Can be extended in your implementation. 
      @param  string - Command 
      @param  callback- Function to Delete from Call List 
      @see  hook 
      @see  trigger_hooks 
      @result  void 
     */ 
     public function unhook($command = NULL,$function) 
     { 
      $command = strtoupper($command); 
      if($command !== NULL) 
      { 
       $k = array_search($function,$this->hooks[$command]); 
       if($k !== FALSE) 
       { 
        unset($this->hooks[$command][$k]); 
       } 
      } else { 
       $k = array_search($this->user_funcs,$function); 
       if($k !== FALSE) 
       { 
        unset($this->user_funcs[$k]); 
       } 
      } 
     } 

     /*! @function loop_once 
      @abstract Runs the class's actions once. 
      @discussion Should only be used if you want to run additional checks during server operation. Otherwise, use infinite_loop() 
      @param  void 
      @see  infinite_loop 
      @result  bool - True 
     */ 
     public function loop_once() 
     { 
      // Setup Clients Listen Socket For Reading 
      $read[0] = $this->master_socket; 
      for($i = 0; $i < $this->max_clients; $i++) 
      { 
       if(isset($this->clients[$i])) 
       { 
        $read[$i + 1] = $this->clients[$i]->socket; 
       } 
      } 

      // Set up a blocking call to socket_select 
      if(socket_select($read,$write = NULL, $except = NULL, $tv_sec = 5) < 1) 
      { 
      // SocketServer::debug("Problem blocking socket_select?"); 
       return true; 
      } 

      // Handle new Connections 
      if(in_array($this->master_socket, $read)) 
      { 
       for($i = 0; $i < $this->max_clients; $i++) 
       { 
        if(empty($this->clients[$i])) 
        { 
         $temp_sock = $this->master_socket; 
         $this->clients[$i] = new SocketServerClient($this->master_socket,$i); 
         $this->trigger_hooks("CONNECT",$this->clients[$i],""); 
         break; 
        } 
        elseif($i == ($this->max_clients-1)) 
        { 
         SocketServer::debug("Too many clients... :("); 
        } 
       } 

      } 

      // Handle Input 
      for($i = 0; $i < $this->max_clients; $i++) // for each client 
      { 
       if(isset($this->clients[$i])) 
       { 
        if(in_array($this->clients[$i]->socket, $read)) 
        { 
         $input = socket_read($this->clients[$i]->socket, $this->max_read); 
         if($input == null) 
         { 
          $this->disconnect($i); 
         } 
         else 
         { 
          SocketServer::debug("{$i}@{$this->clients[$i]->ip} --> {$input}"); 
          $this->trigger_hooks("INPUT",$this->clients[$i],$input); 
         } 
        } 
       } 
      } 
      return true; 
     } 

     /*! @function disconnect 
      @abstract Disconnects a client from the server. 
      @param  int - Index of the client to disconnect. 
      @param  string - Message to send to the hooks 
      @result  void 
     */ 
     public function disconnect($client_index,$message = "") 
     { 
      $i = $client_index; 
      SocketServer::debug("Client {$i} from {$this->clients[$i]->ip} Disconnecting"); 
      $this->trigger_hooks("DISCONNECT",$this->clients[$i],$message); 
      $this->clients[$i]->destroy(); 
      unset($this->clients[$i]);   
     } 

     /*! @function trigger_hooks 
      @abstract Triggers Hooks for a certain command. 
      @param  string - Command who's hooks you want to trigger. 
      @param  object - The client who activated this command. 
      @param  string - The input from the client, or a message to be sent to the hooks. 
      @result  void 
     */ 
     public function trigger_hooks($command,&$client,$input) 
     { 
      if(isset($this->hooks[$command])) 
      { 
       foreach($this->hooks[$command] as $function) 
       { 
        SocketServer::debug("Triggering Hook '{$function}' for '{$command}'"); 
        $continue = call_user_func($function,&$this,&$client,$input); 
        if($continue === FALSE) { break; } 
       } 
      } 
     } 

     /*! @function infinite_loop 
      @abstract Runs the server code until the server is shut down. 
      @see  loop_once 
      @param  void 
      @result  void 
     */ 
     public function infinite_loop() 
     { 
      $test = true; 
      do 
      { 
       $test = $this->loop_once(); 
      } 
      while($test); 
     } 

     /*! @function debug 
      @static 
      @abstract Outputs Text directly. 
      @discussion Yeah, should probably make a way to turn this off. 
      @param  string - Text to Output 
      @result  void 
     */ 
     public static function debug($text) 
     { 
      echo("{$text}\r\n"); 
     } 

     /*! @function socket_write_smart 
      @static 
      @abstract Writes data to the socket, including the length of the data, and ends it with a CRLF unless specified. 
      @discussion It is perfectly valid for socket_write_smart to return zero which means no bytes have been written. Be sure to use the === operator to check for FALSE in case of an error. 
      @param  resource- Socket Instance 
      @param  string - Data to write to the socket. 
      @param  string - Data to end the line with. Specify a "" if you don't want a line end sent. 
      @result  mixed - Returns the number of bytes successfully written to the socket or FALSE on failure. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error. 
     */ 
     public static function socket_write_smart(&$sock,$string,$crlf = "\r\n") 
     { 
      SocketServer::debug("<-- {$string}"); 
      if($crlf) { $string = "{$string}{$crlf}"; } 
      return socket_write($sock,$string,strlen($string)); 
     } 

     /*! @function __get 
      @abstract Magic Method used for allowing the reading of protected variables. 
      @discussion You never need to use this method, simply calling $server->variable works because of this method's existence. 
      @param  string - Variable to retrieve 
      @result  mixed - Returns the reference to the variable called. 
     */ 
     function &__get($name) 
     { 
      return $this->{$name}; 
     } 
    } 

    /*! @class  SocketServerClient 
     @author  Navarr Barnier 
     @abstract A Client Instance for use with SocketServer 
    */ 
    class SocketServerClient 
    { 
     /*! @var  socket 
      @abstract resource - The client's socket resource, for sending and receiving data with. 
     */ 
     protected $socket; 

     /*! @var  ip 
      @abstract string - The client's IP address, as seen by the server. 
     */ 
     protected $ip; 

     /*! @var  hostname 
      @abstract string - The client's hostname, as seen by the server. 
      @discussion This variable is only set after calling lookup_hostname, as hostname lookups can take up a decent amount of time. 
      @see  lookup_hostname 
     */ 
     protected $hostname; 

     /*! @var  server_clients_index 
      @abstract int - The index of this client in the SocketServer's client array. 
     */ 
     protected $server_clients_index; 

     /*! @function __construct 
      @param  resource- The resource of the socket the client is connecting by, generally the master socket. 
      @param  int - The Index in the Server's client array. 
      @result  void 
     */ 
     public function __construct(&$socket,$i) 
     { 
      $this->server_clients_index = $i; 
      $this->socket = socket_accept($socket) or die("Failed to Accept"); 
      SocketServer::debug("New Client Connected"); 
      socket_getpeername($this->socket,$ip); 
      $this->ip = $ip; 
     } 

     /*! @function lookup_hostname 
      @abstract Searches for the user's hostname and stores the result to hostname. 
      @see  hostname 
      @param  void 
      @result  string - The hostname on success or the IP address on failure. 
     */ 
     public function lookup_hostname() 
     { 
      $this->hostname = gethostbyaddr($this->ip); 
      return $this->hostname; 
     } 

     /*! @function destroy 
      @abstract Closes the socket. Thats pretty much it. 
      @param  void 
      @result  void 
     */ 
     public function destroy() 
     { 
      socket_close($this->socket); 
     } 

     function &__get($name) 
     { 
      return $this->{$name}; 
     } 

     function __isset($name) 
     { 
      return isset($this->{$name}); 
     } 
    } 

Source on github

+0

स्क्रिप्ट में अधिक दस्तावेज नहीं हैं, क्या आप क्लाइंट और सीवर कनेक्शन को कैसे शुरू कर सकते हैं इसका अवलोकन कर सकते हैं? धन्यवाद। –

0

वर्तमान शीर्ष उत्तर यहां गलत है, आपको एकाधिक ग्राहकों को संभालने के लिए एकाधिक थ्रेड की आवश्यकता नहीं है। क्रियाशील ग्राहकों से संदेशों को संसाधित करने के लिए आप गैर-अवरुद्ध I/O और stream_select/socket_select का उपयोग कर सकते हैं। मैं socket_* पर stream_socket_* फ़ंक्शंस का उपयोग करने की अनुशंसा करता हूं।

जबकि गैर-अवरुद्ध I/O काफी ठीक काम करता है, आप I/O अवरुद्ध करने के साथ कोई फ़ंक्शन कॉल नहीं कर सकते हैं, अन्यथा I/O अवरुद्ध करने की प्रक्रिया पूरी प्रक्रिया को अवरुद्ध करती है और सभी क्लाइंट केवल एक ही नहीं हैं।

इसका मतलब है कि सभी I/O को गैर-अवरुद्ध होना चाहिए या बहुत तेज़ होने की गारंटी है (जो सही नहीं है, लेकिन स्वीकार्य हो सकता है)। क्योंकि न केवल आपके सॉकेट को stream_select का उपयोग करने की आवश्यकता है, लेकिन आपको सभी खुली धाराओं पर चयन करने की आवश्यकता है, मैं एक लाइब्रेरी की अनुशंसा करता हूं जो स्ट्रीम को पढ़ने योग्य और लिखने योग्य होने के बाद निष्पादित किए गए वॉचर्स को पढ़ने और लिखने के लिए ऑफ़र करता है।

ऐसे कई ढांचे उपलब्ध हैं, सबसे आम ReactPHP और Amp हैं।अंतर्निहित घटना लूप बहुत समान हैं, लेकिन एएमपी उस तरफ कुछ और विशेषताएं प्रदान करता है।

दोनों के बीच मुख्य अंतर एपीआई के लिए दृष्टिकोण है। जबकि ReactPHP हर जगह कॉलबैक का उपयोग करता है, एएमपी कोरआउट का उपयोग करके और इस तरह के उपयोग के लिए अपने एपीआई को अनुकूलित करके उनसे बचने की कोशिश करता है।

एएमपी "प्रारंभ करना" मार्गदर्शिका मूल रूप से इस विषय के बारे में है। आप पूर्ण गाइड here पढ़ सकते हैं। मैं नीचे एक कामकाजी उदाहरण शामिल करूंगा।

<?php 

require __DIR__ . "/vendor/autoload.php"; 

// Non-blocking server implementation based on amphp/socket. 

use Amp\Loop; 
use Amp\Socket\ServerSocket; 
use function Amp\asyncCall; 

Loop::run(function() { 
    $uri = "tcp://127.0.0.1:1337"; 

    $clientHandler = function (ServerSocket $socket) { 
     while (null !== $chunk = yield $socket->read()) { 
      yield $socket->write($chunk); 
     } 
    }; 

    $server = Amp\Socket\listen($uri); 

    while ($socket = yield $server->accept()) { 
     asyncCall($clientHandler, $socket); 
    } 
}); 

Loop::run() घटना पाश चलाता है और टाइमर घटनाओं, संकेतों और कार्रवाई योग्य धाराओं, जो Loop::on*() तरीकों के साथ पंजीकृत किया जा सकता के लिए देखता है। एक सर्वर सॉकेट Amp\Socket\listen() का उपयोग करके बनाया गया है। Server::accept() एक Promise देता है जिसका उपयोग नए क्लाइंट कनेक्शन का इंतजार करने के लिए किया जा सकता है। ग्राहक द्वारा स्वीकार किए जाने के बाद यह एक कोरआउटिन निष्पादित करता है जो क्लाइंट से पढ़ता है और उसी डेटा को गूंजता है। अधिक जानकारी के लिए, एएमपी के दस्तावेज़ीकरण का संदर्भ लें।