php socket創建簡單的HTTP服務器

創建一個http服務器步驟:

  1. 創建socket套接字
  2. 綁定某個地址和端口
  3. 開始監聽,並根據客戶端的請求做出響應
  4. 關閉socket(可以省略,php可以自動回收資源)

PHP代碼

<?php
/**
 * @description HttpServer類
 * @author luoluolzb <[email protected]>
 * @date   2018/3/2
 */
class HttpServer
{
	protected $port;
	protected $address;
	protected $socket;

	/**
	 * 構造函數
	 * @param string  $address 監聽地址
	 * @param integer $port    監聽端口
	 */
	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);
	}

	/**
	 * 開始運行http服務器
	 */
	public function run()
	{
		//開始進行監聽
		socket_listen($this->socket);
		while (true) {
			//獲取請求socket
			$msg_socket = socket_accept($this->socket);
			//獲取請求內容
			$buf = socket_read($msg_socket, 99999);
			echo $buf;  //輸出請求內容
			//寫入相應內容(輸出"Hello World!")
			socket_write($msg_socket, $this->text("Hello World!"));
			//關閉請求socket
			socket_close($msg_socket);
		}
	}

	/**
	 * 獲取http協議的文本內容
	 * @param  string $content string
	 * @return string
	 */
	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();

運行過程

  1. 使用命令行運行腳本 php HttpServer.php
  2. 瀏覽器訪問地址 http://localhost
  3. 查看結果:
  • 控制檯截圖:
    命令行
  • 瀏覽器截圖:
    這裏寫圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章