在 PHP 中,使用 socket_accept()
函數可以接收來自客戶端的連接請求
$server_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$server_socket) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$server_address = "127.0.0.1";
$server_port = 8080;
$bind_result = socket_bind($server_socket, $server_address, $server_port);
if (!$bind_result) {
echo "socket_bind() failed.\nReason: " . socket_strerror(socket_last_error($server_socket)) . "\n";
exit;
}
$listen_result = socket_listen($server_socket, 5);
if (!$listen_result) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($server_socket)) . "\n";
exit;
}
$client_socket = socket_accept($server_socket);
if (!$client_socket) {
echo "socket_accept() failed.\nReason: " . socket_strerror(socket_last_error($server_socket)) . "\n";
exit;
}
$client_data = socket_read($client_socket, 1024);
if ($client_data === false) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($client_socket)) . "\n";
} else {
echo "Received from client: " . $client_data . "\n";
}
$response = "Hello from server!";
socket_write($client_socket, $response);
socket_close($client_socket);
socket_close($server_socket);
將以上代碼片段組合在一起,即可實現一個簡單的 PHP Socket 服務器,使用 socket_accept()
函數接收客戶端連接請求。請注意,這僅是一個基本示例,實際應用中可能需要考慮更多因素,例如錯誤處理、多客戶端支持、安全性和性能優化等。