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 釋放資源 |
php server.phptelnet 127.0.0.1 10000pcntl_signal) 實現優雅關閉。socket_select() 實現多路複用,單進程支援多客戶端。