Skip to content

Automatically exported from code.google.com/p/phpsocketdaemon

License

Notifications You must be signed in to change notification settings

chrischabot/phpsocketdaemon

Repository files navigation

This project came into existence while i was writing a new, ground breaking IRC 
chat web application. To deal with 1000's of concurrent, always on 
(comet aka hanging iframe) http (server) connections, and an equal amount of IRC
client connections, plus being able to interpret and parse and delegate all the 
messages and events, i needed a very fast, stable, flexible and easy to use 'daemon' 
library for PHP.

However no such thing existed yet, hence this library was created.

The tarbal includes a demo HTTP server implimentation, which will give you a good impression
of what its capable off, and how to use this library.

To create a server is as simple as 3 lines of code, for example for our http server:

<?php
	$daemon = new socketDaemon();
	$server = $daemon->create_server('httpdServer', 'httpdServerClient', 0, 2001);
	$daemon->process();
?>

And then a class implementation which deals with the on_read and on_disconnect events.

The socket library takes care of the rest of the IO management (using a socket select loop), read and write buffering (for full asynchronous, non blocking communication) and resource management.

Creating a client with this framework is just as simple:

<?php
	$client = $daemon->create_client('myClientClass', 'remote.com', 80);
?>

And then implimenting a socketClient class, ie:

<?php
class myClientClass extends socketClient {
	public function on_read()
	{
		// handle incomming data which is in $this->read_buffer, forexample the
		// following looks for \r\n, then parses the complete instruction to 'handle_request'
		while (($pos = strpos($this->read_buffer,"\r\n")) !== FALSE) {
			$string = trim(substr($this->read_buffer, 0, $pos + 2));
			$this->read_buffer = substr($this->read_buffer, $pos + 2);
			$this->handle_request($string);
		}
	}

	// other event hooks that exist:
	public function on_connect() {}
	public function on_disconnect() {}
	public function on_read() {}
	public function on_write() {}
	public function on_timer() {}
}
?>

The socket library will deal with all the information that needs to be written (write as much as can be done right away without blocking, and the rest is buffered until it can be written), when data comes in the on_read function is called (check $this->read_buffer to get to it), and connect and disconnect speak for them selves.. The on_timer function is called every 2 seconds (see socketDaemon.php line 97 to change the rate), for dealing with time based events (like the keep-alive time expiring for a http request)

Enjoy & Happy coding!

About

Automatically exported from code.google.com/p/phpsocketdaemon

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published