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.
<?php
$xServer = "localhost";
$xPort = 2002;
$xTimeOut = 10;
$xUser = "XUser";
$xPass = "XPass";
$sarpHandle = fsockopen($xServer, $xPort, &$errNo, &$errStr, $xTimeOut);
if(!$sarpHandle)
{
die("Connection to \"$xServer\" failed.");
}
else
{
echo "Connected<br>";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.
Next: Logging in >>
More PHP Articles
More By Mitchell Harper