Let's demystify swoole : hello world

sebk69

sebk69

Posted on December 9, 2022

Let's demystify swoole : hello world

introduction

Swoole is a PHP extension including async and multithread http server.

In this tutorial, we will create a simple http server which listen to port 9501 and respond a hello world html.

install extension

You are required to have a recent linux distribution debian based (here an Ubuntu 22.04).

Lets install PHP cli :

$ apt-get install php-cli php-pear php-dev
Enter fullscreen mode Exit fullscreen mode

And swoole. Run as root :

$ pecl install swoole
$ echo "extension=swoole.so" > /etc/php/8.1/cli/conf.d/90-swoole.ini 
Enter fullscreen mode Exit fullscreen mode

Create our project

Let's create our directory :

$ mkdir hello-world
$ cd hello-world
Enter fullscreen mode Exit fullscreen mode

Now we will create our index.html file with your favorite editor

<!-- index.html -->
<html>
<body>
<h1>Hello World !</h1> 
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Create the server

Create a file named "serve" with this content :

#!/usr/bin/php
<?php
$server = new \Swoole\Http\Server('0.0.0.0', 9501);
$server->on('Request', function (\Swoole\Http\Request $request, \Swoole\Http\Response $response) {
    $response->write(file_get_contents('index.html'));
    $response->status(200);
    $response->end();
});
$server->start();
Enter fullscreen mode Exit fullscreen mode

Set file executable :

$ chmod 755 serve
Enter fullscreen mode Exit fullscreen mode

Test your server

Run server :

$ ./serve
Enter fullscreen mode Exit fullscreen mode

And go to your favorite browser, to see the result http://localhost:9501.

That's all !

Other posts on swoole

💖 💪 🙅 🚩
sebk69
sebk69

Posted on December 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related