Viewed   65 times

Typical PHP socket functionality is synchronous, and halts the thread when waiting for incoming connections and data. (eg. socket_read and socket_listen)

How do I do the same asynchronously? so I can respond to data in a data received event, instead of polling for data, etc.

 Answers

5

Yup, that's what socket_set_nonblock() is for. Your socket interaction code will need to be written differently, taking into account the special meanings that error codes 11, EWOULDBLOCK, and 115, EINPROGRESS, assume.

Here's some somewhat-fictionalized sample code from a PHP sync socket polling loop, as requested:

$buf = '';
$done = false;
do {
    $chunk = socket_read($sock, 4096);
    if($chunk === false) {
        $error = socket_last_error($sock);
        if($error != 11 && $error != 115) {
            my_error_handler(socket_strerror($error), $error);
            $done = true;
        }
        break;
    } elseif($chunk == '') {
        $done = true;
        break;
    } else { 
        $buf .= $chunk;
    }
} while(true);
Thursday, October 20, 2022
 
2

Here's how to do it. You tell the browser to read in the first N characters of output and then close the connection, while your script keeps running until it's done.

<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort(true); // optional
ob_start();
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Will not work
flush();            // Unless both are called !

// At this point, the browser has closed connection to the web server

// Do processing here
echo('Text user will never see');
?>
Tuesday, August 2, 2022
5

Here's how to do it. You tell the browser to read in the first N characters of output and then close the connection, while your script keeps running until it's done.

<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort(); // optional
ob_start();
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Will not work
flush();            // Unless both are called !

// At this point, the browser has closed connection to the web server

// Do processing here
include('other_script.php');

echo('Text user will never see');
?>
Tuesday, November 1, 2022
 
3

Scripting languages utilize sockets exactly the same way as compiled languages.

1) The script typically opens and uses the socket. It's not "run" or "invoked" by the socket, but directly controls it via libraries (typically calling into the native C API for the OS).

2) Yes.

3) Not necessarily. Most modern scripting langauges can handle multiple sockets in one "script" application.

4) N/A, see 3)


Edit in response to change in question and comments:

This is now obvious that you are trying to run this in the context of a hosted server. Typically, if you're using scripting within Apache or a similar server, things work a bit differently. A socket is opened up and maintained by Apache, and it executes your script, passing the relevant data (POST/GET results, etc.) to your script to process. Sockets usually don't come into play when you're dealing with scripting for CGI, etc.

However, this typically happens using the same concepts as mod_cgi. This pretty much means that the script running is nothing but an executable as far as the server is concerned, and the executable's output is what gets returned to the client. In this case, (provided you have permissions and the correct libraries on the server), your python script can actually launch a separate script that does its own socket work completely outside of Apache's context.

It's (usually) not a good idea to run a full socket implementation directly inside of the CGI script, however. CGI will expect the executable to run to completion before it returns results to the client. Apache will sit there and "hang" a bit waiting for this to complete. If you're launching a full server (especially if it's a long running process, which they tend to be), Apache will think the script is locked, and probably abort, potentially killing the process (configuration specific, but most hosting companies do this to prevent scripts from taking over CPU on a shared system).

However, if you execute a new script from within your script, and then return (shutting down the CGI executable), the other script can be left running, working as a server. This would be something like (python example, using the subprocess library):

newProccess = Popen("python MyScript", shell=True)

Note that all of the above really depends a bit on server configuration, though. Many hosting companies don't include some of the socket or shell libraries in their scripting implementations specifically to prevent this, so you often have to revert to making the executable in C. In addition, this is often against terms of service for most hosting companies - you'd have to check yours.

Saturday, September 17, 2022
 
1

I assume this is a very general question about the relationship between sockets and HTTP connections. I also assume that "HTTPConnection" does not refer to something involving a specific API/runtime/environment even though the way it's a camel cased term with spaces removed could suggest otherwise.

Now that that's out of the way, I present to you, the OSI model:

The OSI Model describes levels of abstraction for network communication. A socket is a concept which would exist somewhere on layer 3, the Network Layer, as part of the Internet Protocol (IP).

HTTP is higher abstraction than IP, usually regarded as being up in the Application Layer, at the "top" of the OSI model.

An Analogy

You could define a city's transportation and traffic at different "layers" the same way we define network stuffs.

  • At its simplest, a city is a bunch of buildings.
  • As the city grows people need to travel from building to building, so they develop roads. The roads are a new "layer" to the city.
  • As more people use the roads, they begin to need a system of rules and laws to help keep everyone safe.
  • Once people are safe on the roads though, they want the roads to be efficient and quick, so a system of lights and signs help coordinate people on the roads.

Two important things:

First, each layer depends on the one "below" it. Without buildings (destinations) roads become silly. Without roads, traffic laws are silly. Without traffic laws, traffic lights are silly.

Second, the specifics of the higher layers vary depending on the city you're in: sometimes you find yourself in a country where people drive on the left, sometimes they drive on the right. Sometimes you can turn on a red, sometimes not. Sometimes there are roads, but they are without laws.

End of Analogy

So on the Internet, sometimes you communicate with different kinds of servers. Underneath, they may all rely on sockets (the "roads" of he internet) but they all have their own "traffic laws" that you have to respect - protocols like HTTP or FTP or SOAP.

Thursday, September 22, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :