PageRenderTime 15ms CodeModel.GetById 10ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/experimental/pherver/Pherver.php

http://zoop.googlecode.com/
PHP | 85 lines | 49 code | 20 blank | 16 comment | 4 complexity | de983f4db656a31ff8de10fdeaf49a99 MD5 | raw file
 1<?php
 2//	this originated from an example on the php website http://us2.php.net/socket_select
 3abstract class Pherver
 4{
 5	protected $clients, $sock;
 6	
 7	function listen($host, $port)
 8	{
 9		$port = 9050;
10
11		// create a streaming socket, of type TCP/IP
12		$this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
13
14		// set the option to reuse the port
15		socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1);
16
17		// "bind" the socket to the address to "localhost", on port $port
18		// so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
19		socket_bind($this->sock, $host, $port);
20
21		// start listen for connections
22		socket_listen($this->sock);
23		
24		return $this->sock;
25	}
26	
27	function run($host, $port)
28	{
29		//	listen on localhost:9050	
30		$this->sock = Pherver::listen($host, $port);
31		
32		// create a list of all the clients that will be connected to us..
33		// add the listening socket to this list
34		$this->clients = array($this->sock);
35
36		while (true)
37		{
38			echo "starting the loop\n";
39			// create a copy, so $this->clients doesn't get modified by socket_select()
40			$read = $this->clients;
41
42			// get a list of all the clients that have data to be read from
43			// if there are no clients with data, go to next iteration
44			echo "selecting a socket\n";
45			
46			$nchanged = socket_select($read, $write = NULL, $except = NULL, 10);
47			
48			if($nchanged === false)
49			{
50				echo "socket_select() failed, reason: " . socket_strerror(socket_last_error()) . "\n";
51				continue;
52			}
53			
54			if($nchanged < 1)
55				continue;
56			
57			echo "printing readable sockets\n";
58			print_r($read);
59
60			// check if there is a client trying to connect
61			if(in_array($this->sock, $read))
62			{
63				// accept the client, and add him to the $this->clients array
64				$this->clients[] = $newsock = socket_accept($this->sock);
65				
66				$this->handleNew($newsock);
67
68				// remove the listening socket from the clients-with-data array
69				$key = array_search($this->sock, $read);
70				unset($read[$key]);
71			}
72
73			// loop through all the clients that have data to read from
74			foreach ($read as $read_sock)
75			{
76				$this->handleRead($read_sock);
77			}
78		}
79		
80		socket_close($this->sock);
81	}
82	
83	abstract protected function handleNew($newsock);
84	abstract protected function handleRead($read_sock);	
85}