PageRenderTime 14ms CodeModel.GetById 11ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/experimental/pherver/ChatServer.php

http://zoop.googlecode.com/
PHP | 49 lines | 32 code | 6 blank | 11 comment | 6 complexity | afed47910da72a2c050bc8702315b917 MD5 | raw file
 1<?php
 2class ChatServer extends Pherver
 3{
 4	protected function handleNew($newsock)
 5	{
 6		// send the client a welcome message
 7		socket_write($newsock, "no noobs, but ill make an exception :)\n".
 8		"There are ".(count($this->clients) - 1)." client(s) connected to the server\n");
 9
10		socket_getpeername($newsock, $ip);
11		echo "New client connected: {$ip}\n";
12	}
13	
14	protected function handleRead($read_sock)
15	{
16		// read until newline or 1024 bytes
17		// socket_read while show errors when the client is disconnected, so silence the error messages
18		$data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);
19
20		// check if the client is disconnected
21		if ($data === false)
22		{
23			// remove client for $this->clients array
24			$key = array_search($read_sock, $this->clients);
25			unset($this->clients[$key]);
26			echo "client disconnected.\n";
27			// continue to the next client to read from, if any
28			continue;
29		}
30
31		// trim off the trailing/beginning white spaces
32		$data = trim($data);
33
34		// check if there is any data after trimming off the spaces
35		if (!empty($data))
36		{	
37			// send this to all the clients in the $this->clients array (except the first one, which is a listening socket)
38			foreach ($this->clients as $send_sock)
39			{
40				// if its the listening sock or the client that we got the message from, go to the next one in the list
41				if ($send_sock == $this->sock || $send_sock == $read_sock)
42					continue;
43
44				// write the message to the client -- add a newline character to the end of the message
45				socket_write($send_sock, $data."\n");
46			}
47		}
48	}
49}