Socket Programming With PHP - On Web-bed Feet (
Page 5 of 9 )
Thus far, I've been
using a standard telnet client to connect to my socket server and interact with
it. However, it's just as easy to write a simple socket client in PHP. Consider
the following example, which requests user input through an HTML form and
creates a client connection to the server demonstrated a few pages back. The
user's input is sent from the client to the server via this newly-minted socket
connection, and the return value from the server (the same string, but reversed)
is displayed to the user on an HTML page.
<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;
// open a client connection
$fp = fsockopen ($host, $port, $errno, $errstr);
if (!$fp)
{
$result = "Error: could not open socket connection";
}
else
{
// get the welcome message
fgets ($fp, 1024);
// write the user string to the socket
fputs ($fp, $message);
// get the result
$result .= fgets ($fp, 1024);
// close the connection
fputs ($fp, "END");
fclose ($fp);
// trim the result and remove the starting ?
$result = trim($result);
$result = substr($result, 2);
// now print it to the browser
}
?>
Server said: <b><? echo $result; ?></b>
<?
}
?>
</body>
</html>