[Sussex] Sockets interface in PHP
Brendan Whelan
b_whelan at mistral.co.uk
Fri Mar 30 13:59:10 UTC 2007
Thanks for the responses.
Have you any pointers to PHP socket programs that us fork() or asynchronous
socket IO?
When I added stream_set_blocking I got:
PHP Warning: stream_set_blocking(): supplied resource is not a valid stream
resource in /..../bw_socket_receive.php on line 31
This seems strange as $sock work elsewhere. As before, the program waits on
the read from the first connection.
Any suggestions? Brendan
----------------------------------------------------------------------------
------
#!/usr/local/bin/php -q
<?php
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";
}
else { echo "socket created\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";
}
if (($error = stream_set_blocking($sock, false) < 0))
{
echo "stream_set_blocking false failed: reason: " . socket_strerror
($sock) . "\n";
}
//if (($error_1 = socket_set_timeout($sock, 1, 0) < 0))
//{
// echo "socket_set_timeout failed: reason: " . socket_strerror ($sock) .
"\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;
}
echo "After read: $buf\n";
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);
?>
More information about the Sussex
mailing list