Connecting to Remote Hosts Using Sockets

Your rating: None Average: 4.7 (3 votes)

When you access a normal file, all file operations ultimately are handled by your computer’s operating system.The operating system creates a resource called a file handle. File handles make it easy for the operating system to understand which file PHP is reading from or writing to.

When you access a (possibly remote) server over the network, all the operations on this connection are also handled by your computer’s operating system. Instead of creating a file handle, the operating system creates a resource called a socket. File handles and sockets are very similar, and through the PHP Streams architecture, PHP tries to keep the differences to a minimum.

When Should I Use a Socket Instead of a File Wrapper?

Some file wrappers allow you to access (possibly remote) network servers. For example, the http file wrapper allows you to retrieve pages from a web server. Unlike sockets, file
wrappers will hide the details of supporting the application-layer network protocol. So why would you want to use a socket instead? You must use a socket if you want to connect to a (possibly remote) network server that there is no file wrapper for. An example would be connecting to the memcached caching server.There is no file wrapper that supports the memcached network protocol. You must use a socket if you want to do something that the file wrapper cannot do—but is possible through the underlying network protocol. An example would be sending an XML-RPC message to a (possibly remote) web server. XML-RPC involves sending
XML messages to and from the web server, using the HTTP network protocol.The http file wrapper only supports reading from a web server; it does allow you to write data to the web server. But the underlying HTTP network protocol does support writing data to a web server, and you can access this network protocol by using a socket rather than by using a file wrapper.

How Do I Open a Socket?
You can create a socket using the fsockopen() and pfsockopen() functions.You tell PHP what type of network transport you want to use by prefixing the transport to the
name or IP address of the server you want to connect to.

<?php
$fp = fsockopen (“tcp://www.php.net”, 80, $sock_errno, $sock_errmsg);
fwrite ($fp, “GET /\n”);
while (!feof($fp))
{
echo fgets($fp) . “\n”;
}
fclose($fp);
?>

Sockets created using fsockopen() are automatically closed by PHP when your script ends. Sockets created using pfsockopen() are persistent.

Persistent Sockets

Sockets created using pfsockopen() remain open after your script has finished. When your next script calls pfsockopen() with the same hostname and port, PHP will reuse
the socket that you opened last time—provided that the socket is still open.

Remote servers (and especially by any firewalls in between) will automatically close persistent sockets if the socket isn’t used for a period of time.

Timeouts When Opening a Socket

If you don’t provide the timeout parameter to fsockopen(), PHP uses the value of default_socket_timeout from the php.ini settings.
The timeout parameter to fsockopen(), and the default_socket_timeout setting, only affect attempts to open the socket.This timeout is not used at all for read and write
operations.
How Do I Use a Socket?
The PHP Streams architecture allows you to treat socket connections as you would another type of stream.To read from a socket, you can use fread() and others.To write to a socket, you can use fwrite() and others.

fread() and fwrite() are binary safe—you can use them to read and write any type of data that you need to.

Blocking Mode
By default, when PHP creates a new socket, it switches on blocking mode for that stream. When blocking mode is on, any functions that attempt to read data from the stream will wait until there is some data available to be read—or until the socket is closed by the remote server.

<?php
$fp = fsockopen(“tcp://www.php.net”, 80, $sock_errno, $sock_errmsg);
echo “Attempting to read from the stream ... this will not timeout\n”;
echo “until the socket closes. You should use CTRL+C to abort this\n”;
echo “script when you’re ready\n”;
echo fgets($fp) . “\n”;
fclose($fp);
?>

You can switch blocking mode off by using stream_set_blocking():

<?php
$fp = fsockopen(“tcp://www.php.net”, 80, $sock_errno, $sock_errmsg);
stream_set_blocking($fp, false);
echo “Attempting to read from the stream ... this will fail and return\n”;
echo “immediately\n\n”;
$result = fgets($fp);
fclose($fp);
echo “fgets() has returned:\n”;
var_dump($result);
?>

Read/Write Timeouts
Instead of switching off blocking mode, you could use stream_set_timeout() to set a timeout on read/write operations instead.

<?php
$fp = fsockopen(“tcp://www.php.net”, 80, $sock_errno, $sock_errmsg);
stream_set_timeout($fp, 10);
echo “Attempting to read from the stream ... this will timeout in 10 secs\n\n”;
$result = fgets($fp);
fclose($fp);
echo “The fgets() has timed out, and returned:\n”;
var_dump($result);
?>

Closing a Socket
When you have finished with a socket, you should close it as soon as possible. The computer that your PHP script is running on can only open a limited number
of sockets.The same is true for the network server at the other end of your socket.The sooner you can close your socket, the sooner the computer’s operating system can recycle the network connection for someone else to use.
Use fclose() to close your socket:

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Cumulus Tag Cloud

Kiran Says

I love work environment which is:

Informal yet professional
Demanding yet rewarding
Challenging yet inspiring
Mediocrity is not an option
Having fun is serious business
Making mistakes is human
Forgiveness is Company Policy

Travelling Sucks