Php multi-process in linux and socket server that can respond to http requests

Source: Internet
Author: User

How painful is it to use php to write http servers? The answer is that it takes the egg to crack.

Fortunately, this is just a little painful, so I wrote something very rough to learn about the usage of php socket (tcp) + fork.

First, let's talk about the principle. The scoket service uses whilet to hook up. After socket_accept receives a new socket connection, it immediately fork a sub-process to interact with the connection separately. This is also very simple, it is nothing more than that socket_read hangs the request listening for this connection. If it finds that some requests are parsed and returned, the return here is the information written by socket_write to the socket connection handle.

The next step is the code. The explanation is not as true as the code.

#! /Usr/local/php/bin/php
<? Php
$ Host = "192.168.1.50"; $ port = 12335;
Set_time_limit (0 );
// Socket create
$ Socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die ("cocould not create socket \ n ");
// Bind socket to a port
$ Result = socket_bind ($ socket, $ host, $ port) or die ("cocould not bind to socket \ n ");
// Start listening for connections
$ Result = socket_listen ($ socket, 3) or die ("cocould not set up socket listener \ n ");

While (true)
{
/** Waiting a new connection **/
$ Newsock = socket_accept ($ socket );
/**
* ** We fork child process for each client
**/
If ($ newsock)
{
$ Child = pcntl_fork ();
If ($ child> 0)
{// Parent process.
/**
** Since child process is hanging there.
** So we know that we shoshould close the client socket here.
**/
Socket_close ($ newsock );
}
Else if ($ child = 0)
{// Child process
/** Get address and port of client socket **/
Socket_getpeername ($ newsock, $ addr, $ port );
$ Welcomemsg = "A new clients $ addr: $ port was entered.". PHP_EOL;
Echo $ welcomemsg;
While (true)
{
/** Hanging here to wait some messages come from client socket **/
$ Msg = socket_read ($ newsock, 1024 );
If ($ msg = false)
{
/** Client was quited unexpected **/
Echo "$ addr: $ port was quited! ". PHP_EOL;
Socket_close ($ newsock );
Posix_kill (posix_getpid (), SIGTERM );
}
Else
{
$ Kill = false;
$ Msg = strtolower (trim ($ msg ));
/** Cli hello message **/
If (! Empty ($ msg) & $ msg! = "\ X21 \ x23") echo "$ addr: $ port request:". $ msg. PHP_EOL;
/** Do something according to command from client **/
Switch ($ msg)
{
Default:
If (preg_match ('# ^ (get | post) \ s +/([^ \ s] *) # I', $ msg, $ match ))
{// It's a http request
$ Page = $ match [2]? $ Match [2]: 'index. php ';
Ob_start ();
Include '/var/www/'. $ page;
$ HttpResponse = ob_get_contents ();
Ob_end_clean ();
// $ HttpResponse = "<B> Hello browser, success! </B> ";
$ Msg = "HTTP/1.1 200 \ n"
. "Content-type: text/html; charset = UTF-8 \ n"
. "Content-length:". strlen ($ httpResponse). "\ n"
. "Connection: close \ n"
. $ HttpResponse;
$ Kill = true;
}
Else $ msg = "Unknow command! ";
Break;
Case "\ x21 \ x23 ":
$ Msg = "Welcome $ addr: $ port ";
Break;

Case 'q ':
Case 'quit ':
Case 'exit ':
Echo "$ addr: $ port ask for quit! ". PHP_EOL;
Break;
}
/** Message send to client socket,
* ** Wocould kill client socket when wrote action was fail or when we doing a http response **/
If (! Socket_write ($ newsock, $ msg, strlen ($ msg) | $ kill)
{
Echo "$ addr: $ port was quited! ". PHP_EOL;
Socket_close ($ newsock );
Posix_kill (posix_getpid (), SIGTERM );
}
}
}
}
Else
{//
Exit ('unable to fork! ');
}
}
}
// Close sockets
Socket_close ($ socket );
?>

Very easy! As I said before, what? I want to parse the http request and return the http request based on cgi.

Try something simple. First, start the socket server service.

  

Then, first browse an html page of the port 80 server.

  

 

Then let's take a look at the php scoket server response results.

  

After a successful response, you can open a browser tab page and enter the address + port to see the correct effect.

In addition, we can see that the browser requested the following information from our silly php http server.

  

Next, how can we improve this php socket server for fun? Let's talk about it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.