Explore swoole — start a hello world with swoole

Time:2021-8-12

catalogue

  1. Explore swoole — start a hello world with swoole

  2. Wonderful use of memory — PHP can finally vs java

  3. Primary application — realize user registration and login [writing]

  4. Outlook — Analysis of the limitations of swoole and my personal expectations [writing]




Old time sake

Remember our first PHP program?

<?php
echo "hello world";

Save him tohello.php, accesshttp://localhost/hello.phpMany people use these two lines of code to introduce PHP

Here we go

Let’s make one with swoole

<?php
$http = new swoole_http_server('0.0.0.0', 80, SWOOLE_BASE);
$http->on('request', function(swoole_http_request $req, swoole_http_response $res) use($http) {
    $res->write("hello world");
    $res->end();
});

OK, see, it doesn’t depend on the framework / ob_ For flush and other mechanisms, swoole can no longer use echo as the output method, so it has to use$res->write(String $content)and$res->end(String $endContent).

So how do we access it?
Command line startup

php app.php
#You echo / VAR in the code_ dump/print(_ r) The content of will be output here

Then open it in the browserhttp://localhost/You can gethello worldOutput of
But did you find it?http://localhost/andhttp://localhost/xxxAll output the same content
If we just want PHPhttp://localhost/How to write the next output?

<?php
$http = new swoole_http_server('0.0.0.0', 80, SWOOLE_BASE);
$http->on('request', function(swoole_http_request $req, swoole_http_response $res) use($http) {
    if($req->server['request_uri'] == '/'){
        $res->write("hello world");
        $res->end();
        return;
    }
    $res->end('404');
    return;
});

\Swoole_http_request $reqIt contains a lot of request data that we can use in the future$req->server, $req->get, $req->post, array structure, and the key of > server is lowercase

In advance, the server data of the swoole HTTP request object is incomplete, and header information such as connection / origin cannot be obtained

[at the end of this section, the text has not been proofread, and the program needs to be tested]