Login   Register  
PHP Classes
elePHPant
Icontem

File: example.php

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of Nathan Bruer  >  Web Socket Service  >  example.php  >  Download  
File: example.php
Role: Example script
Content type: text/plain
Description: Example init script to start a simple chat service
Class: Web Socket Service
Handle Web socket accesses using child processes
Author: By
Last change: fixed minor bug regarding if empty string data sent
Date: 2 years ago
Size: 1,244 bytes
 

Contents

Class file image Download
<?php
// Very Basic Example of a Chat Room Service (no verifiction used [anyone can impersonate anyone])
chdir(__DIR__);
require_once 
'WebSocket.class.php';
require_once 
'WebClientService.class.php';
class 
ChatRoom extends WebClientService{
    const 
ROOM_MESSAGE 'r';
    public function 
dataReceived(){
        
// When data is received from the WebSocket (browser)
        
if($this->currentData)
            
$this->sendToParent(self::ROOM_MESSAGE$this->currentData);
        
Console::log("WS:".print_r($this->currentDatatrue));
    }
    public function 
parentDataRecv($type$data){
        
// When data is received from the parent process
        
switch($type){
            case 
self::ROOM_MESSAGE:
                
Console::log("parentData:".$data);
                if(
$data)
                    
$this->send($data);
                break;
        }
    }
}

// When WebSocket exists it leaves $child and $parent variables available in the global scope.
// $child is the socket to the connection of the WebSocket (browser/user)
// $parent is the socket opened to the parent process for inter-process-communication.
new WebSocket('0.0.0.0'2595);

if(
function_exists('gc_collect_cycles'))
    
gc_collect_cycles();
if(
$child && empty($forked)){
    
$ChatRoom = new ChatRoom($child$parent);
    
$ChatRoom->close();
}
Console::log("Closing process: " getmypid());