Emulating the behavior of a real Web server with low-level sockets is a quite easy process to perform. In this case, I’m not going to use real HTTP commands like GET or POST requests, since it’d be rather pointless (probably you have a production-level Web server already installed on your computer), so instead I’ll create an “always-on” TCP server, which will be capable of fetching a specific (X)HTML file, according to the request made by a client. At the end of this interaction, the contents of this file will be displayed to the user, in this way emulating the interactive process between a real Web server and the corresponding HTTP user agent. Having explained how the Web server will work, here is the PHP class that precisely implements this application. Please, have a look at the code listed below: // define 'WebServer' class As you can see, the above class, which I have amazingly called “WebServer,” implements a basic Web server by using some of the PHP socket-related functions you saw in previous tutorials. Its constructor takes up three arguments: the host to which a connection is established, the TCP port used by the server and the client in conjunction, and finally the physical directory where the server will fetch all the requested files. In order to create a low-level socket and read/write data streams, the class additionally exposes the “createSocket()” method, which also calls the private “readUserInput()” method, handy for reading the name of the file being fetched. Finally, the “fetchFile()” method is tasked with retrieving the contents of the file specified by the client. Before I proceed further, I’d like to clarify one important point: notice that the “fetchFile()” method uses the predefined “C:\php\cli” path, in order to fetch all the requested files. In this case, the server will be run on a Windows system, but if you’re working with Linux or some other operating system, you may want to change this directory and fetch files from another location. Having addressed the topic mentioned before, it’s time to put this Web server to work. Please click on the link below to see an example that shows how the server will retrieve files requested by a Telnet client.
blog comments powered by Disqus |