如何用php實現一個web服務器

如何用php實現一個web服務器

①實現一個回顯服務器

客戶端發來一個請求,咱們把請求包發回去顯示。php

建立監聽套接字

新建start_web.phpgit

<?php
//建立監聽套接字
$web = stream_socket_server('0.0.0.0:8088');

接收請求,並回顯

$conn = @stream_socket_accept($web);
if($conn){
    fwrite($conn,fgets($conn));
    fclose($conn);
}

啓動服務github

php start_web.php //啓動服務

瀏覽器訪問web

http://0.0.0.0:8088/?id=1

顯示結果數組

GET /?id=1 HTTP/1.1

上面的例子在接收客戶端鏈接後,會回顯消息。
可是服務端會中斷服務。
咱們改進一下代碼以下:瀏覽器

<?php
$web = stream_socket_server('0.0.0.0:8088');
while(1){
    $conn = @stream_socket_accept($web);
    if($conn){
        fwrite($conn,fgets($conn));
        fclose($conn);
    }
}

注意 ctrl+c 能夠中斷服務器運行bash

②解析請求報文

要求以下 服務器

  • 區分GETPOSTsocket

  • 獲取請求變量tcp

<?php
$_SERVER = array();
//建立一個tcp套接字,並監聽8088端口
if($web = stream_socket_server('0.0.0.0:8088',$errno,$errstr)){
    while(true){
        $conn = @stream_socket_accept($web);
        if($conn){
            $_SERVER = array();
            decode(fgets($conn));
            fwrite($conn,encode("訪問方法是:".$_SERVER['REQUEST_METHOD']."\n請求變量是:".$_SERVER['QUERY_STRING']));
            fclose($conn);
        }
    }
}else{
    die($errstr);
}
//http協議解碼
function decode($info){
    global $_SERVER;
    list($header,) = explode("\r\n\r\n",$info);
    //將請求頭變爲數組
    $header = explode("\r\n",$header);
    list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header[0]);
    $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
}
//http協議加密
function encode($str){
    $content = "HTTP/1.1 200 OK\r\nServer: vruan_web/1.0.0\r\nContent-Length: " . strlen($str   )."\r\n\r\n{$str}";
    return $content;
}

啓動服務

php start_web.php //啓動服務

瀏覽器訪問

http://0.0.0.0:8088/?id=1&age=19

顯示結果

訪問方法是:GET
請求變量是:id=1&age=19
相關文章
相關標籤/搜索