萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

使用 PHP Socket 實作 C/S 架構伺服器端範例

簡介

PHP 不僅能開發 Web 應用,透過 Socket 擴展也能編寫長期運行的 Client/Server (C/S) 程式。本文提供一個簡單的 TCP 伺服器範例,展示建立 Socket、綁定端口、監聽連線與基本錯誤處理。

伺服器端完整代碼

<?php
// 設定錯誤報告與執行環境
error_reporting(E_ALL);
set_time_limit(0);           // 不限制執行時間
ob_implicit_flush();         // 開啟隱性輸出緩衝

$ip   = '127.0.0.1';         // 監聽 IP
$port = 10000;               // 監聽端口 (建議 >1024 避免權限問題)

// 建立 TCP Socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    die("socket_create() 失敗: " . socket_strerror(socket_last_error()) . "\n");
}
echo "Socket 建立成功\n";

// 綁定 IP 與端口
$bind = socket_bind($socket, $ip, $port);
if ($bind === false) {
    die("socket_bind() 失敗: " . socket_strerror(socket_last_error($socket)) . "\n");
}
echo "Socket 綁定成功\n";

// 開始監聽,backlog 設為 5
$listen = socket_listen($socket, 5);
if ($listen === false) {
    die("socket_listen() 失敗: " . socket_strerror(socket_last_error($socket)) . "\n");
}
echo "等待客戶端連線... (IP: $ip, Port: $port)\n";

while (true) {
    // 接受連線 (阻塞直到有客戶端連入)
    $client = socket_accept($socket);
    if ($client === false) {
        echo "socket_accept() 失敗: " . socket_strerror(socket_last_error($socket)) . "\n";
        continue;
    }
    $client_ip = '';
    $client_port = 0;
    socket_getpeername($client, $client_ip, $client_port);
    echo "客戶端連入: $client_ip:$client_port\n";

    // 讀取客戶端資料 (最多 1024 位元組)
    $data = socket_read($client, 1024);
    if ($data === false) {
        echo "socket_read() 失敗: " . socket_strerror(socket_last_error($client)) . "\n";
    } else {
        echo "收到資料: $data\n";
        // 回應客戶端
        $response = "Server received: $data";
        socket_write($client, $response, strlen($response));
    }

    // 關閉客戶端連線
    socket_close($client);
}

// 關閉主 Socket (實際不會執行到這裡,除非中斷迴圈)
socket_close($socket);
?>

關鍵函數說明

函數用途
socket_create()建立通訊端點,參數分別為域、型別、協定
socket_bind()將 Socket 繫結至指定 IP 與端口
socket_listen()將 Socket 設為被動監聽狀態
socket_accept()接受連線,回傳新的 Socket 資源供通訊使用
socket_read()/socket_write()資料收發
socket_close()關閉 Socket 釋放資源

執行與測試

  1. 終端機執行:php server.php
  2. 另開終端機用 telnet 測試:telnet 127.0.0.1 10000
  3. 輸入文字按 Enter,伺服器將回傳確認訊息。

進階建議

  • 生產環境應加入訊號處理 (pcntl_signal) 實現優雅關閉。
  • 使用 socket_select() 實現多路複用,單進程支援多客戶端。
  • 考慮採用 ReactPHP、Swoole 等高效能非同步框架替代原生 Socket。
copyright © 萬盛學電腦網 all rights reserved