DEV Community

sebk69
sebk69

Posted on • Edited on

5 2

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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay