In PHP, socket programming is an underlying network communication method, suitable for building custom server programs. This article will introduce how to use the socket_accept() function to accept client connections and send a response to the client through the socket_write() function.
First, we need to create a socket resource and bind it to the specified IP address and port to listen to client requests.
<?php
// Create aTCP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
die("socket_create() fail: " . socket_strerror(socket_last_error()) . "\n");
}
// BindIPand ports,假设Bind本地IPand ports8080
$bind = socket_bind($socket, "0.0.0.0", 8080);
if ($bind === false) {
die("socket_bind() fail: " . socket_strerror(socket_last_error($socket)) . "\n");
}
After the binding is successful, we call socket_listen() to start listening, and then use socket_accept() to block and wait for the client to connect.
// Start monitoring,The most allowed5Line up for connections
socket_listen($socket, 5);
echo "Server startup,Waiting for client connection...\n";
while (true) {
// 阻塞Waiting for client connection
$clientSocket = socket_accept($socket);
if ($clientSocket === false) {
echo "socket_accept() fail: " . socket_strerror(socket_last_error($socket)) . "\n";
continue;
}
echo "Client is connected\n";
After receiving the client connection, the client data can be read through socket_read() and send a response to the client using socket_write() . For example, send a simple welcome message.
// Read client data,Maximum read1024byte
$input = socket_read($clientSocket, 1024);
echo "Received a client message: $input\n";
// Send response data
$response = "Welcome to visitm66.netserver!\n";
socket_write($clientSocket, $response, strlen($response));
// Close client connection
socket_close($clientSocket);
}
When the server needs to be shut down, call socket_close() to release the resource.
socket_close($socket);
The above code shows a simple PHP socket-based server example, with the focus on:
Use socket_create() to create socket;
Use socket_bind() to bind IP and port;
Use socket_listen() to start listening;
Use socket_accept() to block waiting for client connection;
Use socket_write() to send data responses to the client.
In this way, you can build a basic TCP server through PHP native socket programming, and flexibly handle client connections and communications.