在 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()
函数接收客户端连接请求。请注意,这仅是一个基本示例,实际应用中可能需要考虑更多因素,例如错误处理、多客户端支持、安全性和性能优化等。