This section uses php native socket to demonstrate the principle of HTTP request
A typical network connection consists of two sockets, one running on the client and the other on the server.
Socket is called socket. In network programming, it is called “software device” for network data transmission.
Well, to understand it, socket is a file resource
Process summary: suppose the scenario is Shicheng, a ramen shop. adopt
createTo create a server socket, there are three parameters to initialize the socket: IPv4 or IPv6, connection oriented or message oriented, TCP or UDP. That is to say, what is the socket used for and I am a noodle shop. Next, through the
bindPort number, which is the contact address, food city 123 can find me. adopt
listenStart monitoring, ready to start business (no one in the store at this time, customers wait in line). call
acceptThe function waits for the client connection (blocked here until a client connection generates a client file descriptor FD), that is, waits for the guest until a customer comes. At this time, the clerk picks up a piece of paper and asks the customer what to eat, and then transfers the paper to the kitchen. Back kitchen
readThe dishes on the paper, and then prepare the food
response, and then
writeFor customers. If the customer leaves, the card will be useless and thrown away (FD recycling),
close。 The ramen shop is closed,
Create a socket,
$serverIt meansServerSocket for.
$server = socket_create( AF_INET, SOCK_STREAM, SOL_TCP);
Binding port number,
0.0.0.0Service for all, of course, can also be dedicated
socket_bind($socket, '0.0.0.0', 80);
5The number of customers waiting for reception in the queue is only 5 at the local gate (resource level).
Establishing a connection with a client
$client = socket_accept($server);
Read client signal
$buf = socket_read($client, 1024);
$content = 'hello! i am server!'; $http_resonse = "HTTP/1.1 200 OK\r\n"; $http_resonse .= "Content-Type: text/html;charset=UTF-8\r\n"; $http_resonse .= "Connection: keep-alive\r\n"; $http_resonse .= "Server: php socket server\r\n"; $http_resonse .= "Content-length: ".strlen($content)."\r\n\r\n"; $http_resonse .= $content;
Write signal to client
Close the client and recycle the resources. The resource descriptors created by the system are limited (because each resource descriptor has to open the input / output buffer. If the resource is not reclaimed in time, the memory will be full)
Close the server
If the address I requested is as follows:
BUF is a long string that is matched with a regular string:
$preg = '#GET (.*) HTTP/1.1#iU'; preg_match($preg, $buf, $arr); $request = $arr;
So we get the content of the request.
The file name obtained is
$filePath = __DIR__ . '/html' . $path; $content = file_get_contents($filePath);
The obtained file name is:
$filePath = __ DIR__ . '/ php' . $path;
This work adoptsCC agreementReprint must indicate the author and the link of this article