使用原生PHP构建一个简单的PHPWeb服务器

1.目录机构

webserver
--src
-- Response.php
-- Server.php
-- Request.php
-- vendor
-- Server.php
-- composer.json

2. 使用comoposer构建自动加载

编辑`comooser.json`文件

{
"autoload": {
"psr-4": {
"Icarus\\Station\\PHPServer\\": "src/"
}
}
}

使用PSR-4自动加载方式构建自动加载

3. 编写 Server文件

该文件作为启动文件,使用以下命令 php Server 8080 启动服务

<?php

use Icarus\Station\PHPServer\Server;
use Icarus\Station\PHPServer\Request;
use Icarus\Station\PHPServer\Response; array_shift($argv); //获取端口号
if (empty($argv)) {
$port = 80;
}else {
$port = (int)array_shift($argv);
} require_once "./vendor/autoload.php"; $server = new Server("127.0.0.1",$port); $server->listen(function(Request $request){
return new Response("Hello World!");
});

4. 编写Response.php

该类实现对请求的响应

<?php

namespace Icarus\Station\PHPServer;

class Response
{
protected static $statusCodes = [
100 => 'Continue',
101 => 'Switching Protocols', // Success 2xx
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content', // Redirection 3xx
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
// 306 is deprecated but reserved
307 => 'Temporary Redirect', // Client Error 4xx
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed', // Server Error 5xx
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
509 => 'Bandwidth Limit Exceeded'
]; protected $status = 200;
protected $body = '';
protected $headers = []; public function __construct($body, $status = null)
{
if (!is_null($status)) {
$this->status = $status;
}
$this->body = $body;
$this->header('Date', gmdate('D, d M Y H:i:s T'));
$this->header('Content-Type', 'text/html; charset=utf-8');
$this->header('Server', 'PHPServer/1.0.0');
} public function header($key, $val)
{
$this->headers[ucwords($key)] = $val;
} public function buildHeaderString()
{
$lines = [];
$lines[] = "HTTP/1.1 " . $this->status . " " . static::$statusCodes[$this->status]; foreach ($this->headers as $key => $value) {
$lines[] = $key . ": " . $value;
} return implode(" \r\n", $lines) . "\r\n\r\n";
} public static function error($statusCode)
{
header(self::$statusCodes[$statusCode], '', $statusCode);
} public function __toString()
{
return $this->buildHeaderString() . $this->body;
}
}

5. 编写Request.php

该类主要实现请求的解析(暂时为GET请求)

<?php

namespace Icarus\Station\PHPServer;

class Request
{
protected $uri = '';
protected $method = '';
protected $params = [];
protected $headers = []; public function __construct($method, $uri, $headers)
{
$this->method = strtolower($method);
$this->headers = $headers;
list($this->uri, $param) = explode('?', $uri);
parse_str($param, $this->params);
} public function method()
{
return $this->method;
} public function headers($key, $default = null)
{
if (isset($this->headers[$key])) {
$default = $this->headers[$key];
}
return $default;
} public function uri()
{
return $this->uri;
} public function params($key, $default = null)
{
if (isset($this->params[$key])) {
$default = $this->params($key);
}
return $default;
} public static function withHeaderString($data)
{
$headers = explode("\n", $data);
list($method, $uri) = explode(" ", array_shift($headers));
$header = [];
foreach ($headers as $value) {
$value = trim($value);
if (strpos($value, ":") !== false) {
list($key, $value) = explode(":", $value);
$header[$key] = $value;
}
}
return new static($method, $uri, $header);
} public function __toString()
{
return json_encode($this->headers);
}
}

6.编写Server.php

该模块主要实现对socket的封装。

<?php

namespace Icarus\Station\PHPServer;

class Server
{ protected $host = null;
protected $port = null;
protected $socket = null; public function __construct($host, $port)
{
$this->host = $host;
$this->port = $port;
$this->createSocket();
$this->bind();
} protected function createSocket()
{
$this->socket = socket_create(AF_INET, SOCK_STREAM, 0);
} protected function bind()
{
if (!socket_bind($this->socket,$this->host, $this->port)) {
throw new \Exception("未能绑定socket: " . $this->host . $this->port . socket_strerror(socket_last_error()));
} } public function listen(callable $callback)
{
while (true) {
socket_listen($this->socket);
if (!$client = socket_accept($this->socket)) {
socket_close($client);
continue;
}
$data = socket_read($client, 1024);
$request = Request::withHeaderString($data);
$response = call_user_func($callback, $request);
if (!$response | !$response instanceof Response) {
$response = Response::error(404);
}
$response = (string)$response;
socket_write($client,$response,strlen($response));
socket_close($client);
}
}
}

7. 使用

1. 进入到项目目录
2. 执行` php Server 8080`
3. 另起一个终端,执行 `curl "http://127.0.0.1:8080`
4. 显示 `Hello World!`

8. 总结

该demo使用socket来实现一个简单的webserver,但是由于php不支持多线程的的特性(其实也能实现,不过需要安装pthreads扩展),还是不适合开发webserver,此demo主要用来学习webserver的概念。

此demo参考了http://station.clancats.com/writing-a-webserver-in-pure-php/的讲解及实现。

最新文章

  1. Qt json 数据处理
  2. mysql创建外键出错(注意数据库表字段排序)
  3. 97、进入ScrollView根布局页面,直接跳到页面底部,不能显示顶部内容
  4. JSON和XML的比较
  5. Python:运算符
  6. android-Java SoftReference,WeakReference,Direct Reference简介
  7. BZOJ 1509: [NOI2003]逃学的小孩( 树形dp )
  8. LeetCode OJ 292.Nim Gam148. Sort List
  9. Android EventBus 3.0 实例使用详解
  10. document.forms[].submit()
  11. Docker - rm 命令
  12. SQL 从一个表读取数据存到另一个表
  13. 2018 Benelux Algorithm Programming Contest (BAPC 18)I In Case of an Invasion, Please. . .
  14. Docker容器里的进程为什么要前台运行?相同的问题:docker运行apache为什么带FOREGROUND参数?docker运行nginx为什么带`daemon off`参数?
  15. linux 驱动之LCD驱动(有framebuffer)
  16. git操命令&amp;&amp;node操作命令
  17. 【AUC】二分类模型的评价指标ROC Curve
  18. Android的读写文件及权限设置
  19. 在Eclipse中生成javadoc
  20. 20162324 2016-2017-2《Java程序设计》课程总结

热门文章

  1. mac os安裝jdk
  2. JS基础入门篇(三)— for循环,取余,取整。
  3. windows2008R2-AD域控组策略设置与其它相关设置
  4. No module named flask 导包失败,Python3重新安装Flask模块
  5. Task9.Attention
  6. 循环神经网络(LSTM和GRU)(2)
  7. Linux 系统参数优化
  8. FPGA资源平民化的新晋- F9 技术解析
  9. C# 获取路径中,文件名、目录、扩展名等
  10. 2、投资之基金 - IT人思维之投资