Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function echoClients(array $clients) {
- if (count($clients) == 0) {
- echo "No clients connected.\n";
- return;
- }
- $names = array();
- foreach ($clients as $client) {
- if (!is_null($client['name']))
- $names[] = $client['name'];
- }
- echo "Clients connected: ".implode(', ', $names).".\n";
- }
- $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
- socket_bind($socket, '127.0.0.1', 100);
- socket_listen($socket);
- $clients = array();
- while (true) {
- $read = array($socket);
- foreach ($clients as $client) {
- $read[] = $client['socket'];
- }
- $ready = socket_select($read, $write = null, $except = null, null);
- if (in_array($socket, $read, true)) {
- $clients[] = array(
- 'socket' => socket_accept($socket),
- 'name' => null
- );
- socket_write($clients[count($clients)-1]['socket'], "Welcome to ChatServer!\nWrite your name: ");
- $ready--;
- }
- if ($ready == 0) continue;
- $num_clients = count($clients);
- for ($i = 0; $i < $num_clients; $i++) {
- if (in_array($clients[$i]['socket'], $read, true)) {
- $input = socket_read($clients[$i]['socket'], 256);
- if (empty($input)) {
- socket_close($clients[$i]['socket']);
- echo "--{$clients[$i]['name']} has left. ";
- unset($clients[$i]);
- echoClients($clients);
- }
- else {
- if (is_null($clients[$i]['name'])) {
- $clients[$i]['name'] = trim(preg_replace('/\s/', ' ', $input));
- echo "--{$clients[$i]['name']} has joined. ";
- echoClients($clients);
- }
- else {
- echo "{$clients[$i]['name']} says: $input";
- }
- }
- }
- }
- $clients = array_merge(array(), $clients);
- }
- socket_close($socket);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement