In this article, Mitchell shows us how to implement our custom SARP protocol that we created yesterday. He uses PHP and its various socket functions to send SARP commands to our SARP server to both retrieve articles and add new articles to the servers Access database.
Building A Document Request Protocol Part 2/2 - Connecting to our SARP server (Page 2 of 6 )
PHP supports socket connections using either the TCP or UDP protocols. The fsockopen function creates a socket connection to another computer, allowing us to specify that computers IP address, required port, and even a connection time out. Its signature looks like this:
int fsockopen (string hostname, int port [, int errno [, string errstr [, float timeout]]])
Fsockopen returns 1 if the socket was created successfully, and 0 if it failed. The errno and errstr variables are passed in by reference, and will contain the details of an error if it occurs.
To connect to our SARP server (remember that our "SARP server" is simply the VB app that we created in part one of this article running on the local machine), we can define some variables and use fsockopen to create a socket connection. Create a new file named sarp_test.php and save it in a directory that either Apache/IIS can process. Enter all of the code described over the next couple of sections into the file.
As you can see, we're creating a socket that binds to port 2002 on the server and has a timeout of ten seconds, meaning that if a connection to the server can't be established within ten seconds, then fsockopen will return false.
If the socket couldn't be created, then the die() function outputs a connection failed message to the browser and terminates the script. On the other hand, if the connection succeeded, then we can place code inside of the else block to send data to and from that server.