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