Feautures:
Optional:
require_once dirname(__FILE__).'/websocketserver/server.php';
class ChatUser extends WSBaseUser {
protected $maxIdle = 10;
}
class ChatConfig extends WSBaseConfig {
public $address = 'localhost';
public $post = 12345;
public $userClass = 'ChatUser';
}
class ChatServer extends WebSocketServer {
protected $configClass = 'ChatConfig';
function process($user, $msg){
$this->sentToAllBut($user, $msg);
}
}
$server = new ChatServer();
$server->run();
Available hooks that may be implemented:
preSend
function preSend(&$user, &$msg)
postSend
function postSend(&$user, &$msg)
preConnect
function preConnect(&$user, $socket)
postConnect
function postConnect(&$user, $socket)
preDisconnect
function preDisconnect(&$user, $socket)
postDisconnect
function postDisconnect()
preShutdown:
function preShutdown(&$doShutdown)
postShutdown
function postShutdown()
Implementing these hooks is done by creating a method with that name in the class that extends WebSocketServer. Some parameters are passed by reference, meaning that hooks don't only provide information from the server, but also allows influencing its behaviour. In cases where a user is passed to a hook, the actual user object is available, so any methods that were added to the use class by extending it, are available in these hooks.
In the following, $user is the complete user object, and $msg is the message (string, array or object) to send to the client.
Send to one specific user
sendToUser($user, $msg)
Send to all users
sendToAll($msg)
Send to all users, except one
sendToAllBut($user, $msg)
The server adds the opening and closing characters for correctly sending it over a socket connection, and removes them when a message is received. If you send an object or array as message, the server will encode it to json. If the server receives a message in json format, it will be converted to an object or array for internal use. All hooks and the process method can use objects and arrays as messages, the server will do the conversion where appropriate.
The server can be configured to allow connections from any origin, or you may supply a list of allowed origins. Please see config.class.php for more details.
A big thank you goes to georgenava, whose example code was great for learning how to do a basic implementation of websockets in PHP. The run() method in my implementation and some other parts are taken almost literally from his code at http://code.google.com/p/phpwebsocket/ and https://github.com/GeorgeNava/phpwebsocket