#!/usr/bin/php -q
<?php  /*  >php -q server.php  */

error_reporting(E_ALL);
ini_set('display_errors'true);
set_time_limit(0);
ob_implicit_flush();


Class 
WebsocketChat {

    
    
/**
     * @var array
     */
    
private $messages = array();

    
    
/**
     * callback function 
     * @param WebSocketUser $user Current user
     * @param string $msg Data from user sent
     * @param WebSocketServer $server Server object
     */
    
public function process($user$msg$server){

        
$msg json_decode($msg);
        
        if (
$msg->action == 'init') {
            
$max 5;
            if (
count($this->messages)<5)
                
$max count($this->messages);
            
            
// on login send last five chat messages
            
for($i=count($this->messages)-$max$i<count($this->messages); $i++) {
                
$server->send($user->socket, (string) $this->messages[$i]);
            }            
        }
        
        if (
$msg->action == 'login') {
            
$user->data['username'] = filter_var($msg->usernameFILTER_SANITIZE_STRING);
        }
        
        if (
$msg->action == 'chat') {
            
$text filter_var($msg->textFILTER_SANITIZE_STRING);    
            
$lastMessage = new WebsocketChatMessage($user->data['username'], $texttime());
            
            
$user->data['message'][] = $this->messages[] = $lastMessage;
            
            foreach(
$server->getUsers() as $user){
                
$server->send($user->socket, (string) $lastMessage);
            }            
        }

    }
}

Class 
WebsocketChatMessage {
    
    public 
$text '';
    
    public 
$timestamp 0;
    
    public 
$username '';
    
    public function 
__construct($username$text$timestamp) {
        
$this->text $text;
        
$this->username $username;
        
$this->timestamp $timestamp;
    }
    
    public function 
__toString() {
        return 
sprintf('%s - %s: %s'strftime('%H:%M'$this->timestamp), $this->username$this->text);
    }
}    


date_default_timezone_set('Europe/Berlin');
require_once 
'WebSocketServer.php';

$chat = new WebsocketChat();
// new WebSocketServer( socket address, socket port, callback function )
$webSocket = new WebSocketServer("84.38.67.247"8081, array($chat'process'));
$webSocket->run();



BOHUCO Labs / HTML5 WebSocket Chat with PHP5 Server
Enter to send!