如何用PHP實現Socket伺服器

來源:互聯網
上載者:User

想要構建聊天應用,或者甚至是遊戲嗎?那麼,socket伺服器將成為你邁出的第一步。一旦你瞭解了建立伺服器的準系統,那麼後續的最佳化步驟就會變得同樣簡單。

socket伺服器的工作方式是這樣的,不間斷地運行以等待用戶端的串連。一旦用戶端串連上了,伺服器就會將它添加到客戶名單中,然後開始等待來自用戶端的訊息。

不要走開,下面是完整的原始碼:

 
  1. // Set time limit to indefinite execution 
  2. set_time_limit (0); 
  3.  
  4. // Set the ip and port we will listen on 
  5. $address = 'localhost'; 
  6. $port = 10000; 
  7. $max_clients = 10; 
  8.  
  9. // Array that will hold client information 
  10. $client = Array(); 
  11.  
  12. // Create a TCP Stream socket 
  13. $sock = socket_create(AF_INET, SOCK_STREAM, 0); 
  14. // Bind the socket to an address/port 
  15. socket_bind($sock, $address, $port) or die('Could not bind to address'); 
  16. // Start listening for connections 
  17. socket_listen($sock); 
  18.  
  19. echo "Waiting for connections...\r\n"; 
  20.  
  21. // Loop continuously 
  22. while (true) { 
  23. // Setup clients listen socket for reading 
  24. $read[0] = $sock; 
  25. for ($i = 0; $i < $max_clients; $i++) { 
  26.   if (isset($client[$i]['sock'])) 
  27.    $read[$i + 1] = $client[$i]['sock']; 
  28. // Set up a blocking call to socket_select() 
  29. if (socket_select($read, $write = NULL, $except = NULL, $tv_sec = 5) < 1) 
  30.   continue; 
  31. /* if a new connection is being made add it to the client array */ 
  32. if (in_array($sock, $read)) { 
  33.   for ($i = 0; $i < $max_clients; $i++) { 
  34.    if (empty($client[$i]['sock'])) { 
  35.     $client[$i]['sock'] = socket_accept($sock); 
  36.     echo "New client connected $i\r\n"; 
  37.     break; 
  38.    } 
  39.    elseif ($i == $max_clients - 1) 
  40.     echo "Too many clients...\r\n"; 
  41.   } 
  42. } // end if in_array 
  43.  
  44. // If a client is trying to write - handle it now 
  45. for ($i = 0; $i < $max_clients; $i++) { // for each client 
  46.   if (isset($client[$i]['sock'])) { 
  47.    if (in_array($client[$i]['sock'], $read)) { 
  48.     $input = socket_read($client[$i]['sock'], 1024); 
  49.     if ($input == null) { 
  50.      echo "Client disconnecting $i\r\n"; 
  51.      // Zero length string meaning disconnected 
  52.      unset($client[$i]); 
  53.     } else { 
  54.      echo "New input received $i\r\n"; 
  55.      // send it to the other clients 
  56.      for ($j = 0; $j < $max_clients; $j++) { 
  57.       if (isset($client[$j]['sock']) && $j != $i) { 
  58.        echo "Writing '$input' to client $j\r\n"; 
  59.        socket_write($client[$j]['sock'], $input, strlen($input)); 
  60.       } 
  61.      } 
  62.      if ($input == 'exit') { 
  63.       // requested disconnect 
  64.       socket_close($client[$i]['sock']); 
  65.      } 
  66.     } 
  67.    } else { 
  68.     echo "Client disconnected $i\r\n"; 
  69.     // Close the socket 
  70.     socket_close($client[$i]['sock']); 
  71.     unset($client[$i]); 
  72.    } 
  73.   } 
  74. } // end while 
  75. // Close the master sockets 
  76. socket_close($sock); 

啊呀,乍一看這似乎是一個大工程,但是我們可以先將它分解為幾個較小的部分。第一部分是建立伺服器。Lines:2至20。

這部分代碼設定了變數、地址、連接埠、最大用戶端和用戶端數組。接下來建立socket並將其綁定到我們指定的地址和連接埠上。

下面我們要做的事情就是執行一個死迴圈(實際上我們是故意的!)。Lines:22至32。在這部分代碼中我們做的第一步是設定 $read 數組。此數 組包含所有用戶端的通訊端和我們主伺服器的通訊端。這個變數稍後會用於select語句:告訴PHP監聽來自這些用戶端的每一條訊息。

socket_select()的最後一個參數告訴我們的伺服器在傳回值之前最多等待5秒鐘。如果它的傳回值小於1,那麼就表示沒有收到任何資料,所以只需要返回迴圈頂部,繼續等待。

指令碼的下一個部分,是增加新的用戶端到數組中。Lines:33至44。

將新的用戶端放置在列表的末尾。檢查以確保用戶端的數量沒有超過我們想要伺服器處理的數量。

下面要介紹的代碼塊相當大,也是伺服器的主要部分。當用戶端將訊息發送到伺服器時,就需要這塊代碼挺身而出來處理。訊息可以是各種各樣的,斷開訊息、實際斷開——只要是伺服器需要處理的訊息。Lines:46至末尾。

代碼迴圈通過每個用戶端並檢查是否收到來自於它們的訊息。如果是,擷取輸入的內容。根據輸入來檢查這是否是一個斷開訊息,如果是那就從數組中刪除它們,反之,那它就是一個正常的訊息,那我們的伺服器再次通過所有用戶端,並一個一個寫資訊給他們,跳過寄件者。

好了,下面試試創造你自己的聊天伺服器吧!



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.