[Sussex] Sockets interface in PHP
Brendan Whelan
b_whelan at mistral.co.uk
Fri Mar 30 09:32:59 UTC 2007
I am developing a sockets interface, in PHP running under Fedora Core 5, to receive requests and return data. See below is the program in its most basic form. It accepts requests and returns data but the program waits on the socket_read and only moves on when either data is received or the sending system terminates the connection. This means that other users/systems cannot gain access. I have hunted around the Internet and tried various combinations without success.
Any suggestions?
Thanks, Brendan
#!/usr/local/bin/php -q
<?php
// Simple sockets receive program
error_reporting (E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit (0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush ();
print "Started\n";
$address = '192.168.40.19';
// PORT NEEDS TO BE PERMITTED THROUGH FIREWALL
$port = 21244;
if (($sock = socket_create (AF_INET, SOCK_STREAM, 0)) < 0) {
echo "socket_create() failed: reason: " . socket_strerror ($sock) . "\n";
}
if (($ret = socket_bind ($sock, $address, $port)) < 0) {
echo "socket_bind() failed: reason: " . socket_strerror ($ret) . "\n";
}
if (($ret = socket_listen ($sock, 5)) < 0) {
echo "socket_listen() failed: reason: " . socket_strerror ($ret) . "\n";
}
do {
print "In loop\n";
if (($msgsock = socket_accept($sock)) < 0) {
echo "socket_accept() failed: reason: " . socket_strerror ($msgsock) . "\n";
break;
}
print "After accept\n";
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
print "Above inner loop\n";
do {
if (FALSE === ($buf = socket_read ($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror ($ret) . "\n";
break 2;
}
if (!$buf = trim ($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close ($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
socket_write ($msgsock, $talkback, strlen ($talkback));
echo "$buf\n";
} while (true);
socket_close ($msgsock);
} while (true);
socket_close ($sock);
?>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mailman.lug.org.uk/pipermail/sussex/attachments/20070330/082322c8/attachment.htm
More information about the Sussex
mailing list