创建一个http服务器步骤:
- 创建socket套接字
- 绑定某个地址和端口
- 开始监听,并根据客户端的请求做出响应
- 关闭socket(可以省略,php可以自动回收资源)
PHP代码
<?php
class HttpServer
{
protected $port;
protected $address;
protected $socket;
public function __construct($address = 'localhost', $port = 80)
{
$this->port = $port;
$this->address = $address;
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (! $this->socket) {
throw new Exception("Http Server create failed!");
}
socket_bind($this->socket, $address, $this->port);
}
public function __destruct()
{
socket_close($this->socket);
}
public function run()
{
socket_listen($this->socket);
while (true) {
$msg_socket = socket_accept($this->socket);
$buf = socket_read($msg_socket, 99999);
echo $buf;
socket_write($msg_socket, $this->text("Hello World!"));
socket_close($msg_socket);
}
}
private function text($content)
{
$text = 'HTTP/1.0 200 OK' . "\r\n";
$text .= 'Content-Type: text/plain' . "\r\n";
$text .= 'Content-Length: ' . strlen($content) . "\r\n";
$text .= "\r\n";
$text .= $content;
return $text;
}
}
$server = new HttpServer();
echo "Server running at http://localhost\r\n";
$server->run();
运行过程
- 使用命令行运行脚本
php HttpServer.php
- 浏览器访问地址
http://localhost
- 查看结果:
- 控制台截图:
- 浏览器截图: