創建一個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
- 查看結果:
- 控制檯截圖:
- 瀏覽器截圖: