You might not know this, but PHP comes with a very capable socketprogramming API. These socket functions now include almost everything youwould need for socket-based client-server communication over TCP/IP, andcan be easily deployed to build simple network applications. Find out more,inside.
If you'd prefer to, there's also an alternative, somewhat longer approach to constructing a client. Most of the time, you won't need to use this - fsockopen() is more than sufficient for most requirements - but it's included here for reference purposes. Take a look at this next script, which replicates the functionality of the previous example:
<html>
<head>
</head>
<body>
<?
// form not yet submitted
if (!$submit)
{
?>
<form action="<? echo $PHP_SELF; ?>" method="post">
Enter some text:<br>
<input type="Text" name="message" size="15"><input type="submit"
name="submit" value="Send">
</form>
<?
}
else
{
// form submitted
// where is the socket server?
$host="192.168.1.99";
$port = 1234;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create
socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect
to server\n");
socket_read ($socket, 1024) or die("Could not read server response\n");
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send
data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server
response\n");
// end session
socket_write($socket, "END", 3) or die("Could not end session\n");
// close socket
socket_close($socket);
// clean up result
$result = trim($result);
$result = substr($result, 0, strlen($result)-1);
// print result to browser
?>
Server said: <b><? echo $result; ?></b>
<?
}
?>
</body>
</html>
In this case, the socket_connect() function is used to open a
connection to the server, with the familiar socket_read() and socket_write() functions used to receive and transmit data over the socket connection. Once the result string has been obtained from the server, the socket connection is closed with socket_close() and the output is printed to the browser.
Again, this is an alternative implementation - it's unlikely that you'll find much use for it, as the fsockopen() function provides a much simpler (and shorter) way to accomplish the same thing.