note 112299 deleted from sockets.examples by danbrown
| From: | danbrown@php.net | Date: | Wed, 05 Jun 2013 17:40:24 +0000 |
| Subject: | note 112299 deleted from sockets.examples by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-195063@lists.php.net to get a copy of this message | ||
Note Submitter: Rosekrans, vulco dot jacques at gmail
----
A big thanks to javier,javiern at gmail dot com. This was exactly what I was looking for. I have
taken the liberty to translate some of the text. I hope you don't mind...
#!/usr/bin/env php
<?php
error_reporting(E_ALL);
/* Allow the script to wait for connections. */
set_time_limit(0);
/* Enable implicit dump and see what estimate is obtained while waiting. */
ob_implicit_flush();
$address = '127.0.0.1';
$port = 8011;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) .
"\n";
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) .
"\n";
}
if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) .
"\n";
}
//clients array
$clients = array();
do {
$read = array();
$read[] = $sock;
$read = array_merge($read,$clients);
// Set up a blocking call to socket_select
if(socket_select($read,$write = NULL, $except = NULL, $tv_sec = 5) < 1)
{
// SocketServer::debug("Problem blocking socket_select?");
continue;
}
// Handle new Connections
if (in_array($sock, $read)) {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " .
socket_strerror(socket_last_error($sock)) . "\n";
break;
}
$clients[] = $msgsock;
$key = array_keys($clients, $msgsock);
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"You are the customer number: {$key[0]}\n" .
"To exit, type 'quit'. To shut down the server type
'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
}
// Handle Input
foreach ($clients as $key => $client) { // for each client
if (in_array($client, $read)) {
if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " .
socket_strerror(socket_last_error($client)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
unset($clients[$key]);
socket_close($client);
break;
}
if ($buf == 'shutdown') {
socket_close($client);
break 2;
}
$talkback = "Customer {$key}: You said '$buf'.\n";
socket_write($client, $talkback, strlen($talkback));
echo "$buf\n";
}
}
} while (true);
socket_close($sock);
?>