danny.cain/unix-sockets

dev-master 2018-08-12 19:38 UTC

README

Allows inter process communication and the running of "single instance" apps, apps where trying to run it a second time, will instead send a command the to the already running instance.

Usage

For basic Unix Sockets see /example/app.php For two-way single instance, see /example/single-instance.php

The Single instance classes accept any type of data, the data will be bundled into a json object that is then passed to the server. A factory function has been provided in /classes/include.php to aid with building a SingleInstance app

Single Instance

<?php
use DannyCain\UnixSockets\SingleInstance\SingleInstanceClient;
use DannyCain\UnixSockets\SingleInstance\SingleInstanceServer;

# define socket file to use
$comms = SingleInstanceFactory('/tmp/single-instance.sock');
if ($comms instanceof SingleInstanceClient) {
    $opts = getopt('q');
    if (isset($opts['q'])) {
        $comms->write(array('action' => 'quit'));
    } else {
        $comms->write(array('action' => 'speak'));
        $responses = array();
        
        while(count($responses) == 0) {
            $responses = $comms->read();
        }
        
        foreach($responses as $response) {
            echo $response['response']."\n";
        }
    }
} else {
    $count = 0;
    $running = true;
    
    while($running) {
        sleep(1);
        $count ++;
        
        foreach($comms->read() as $message) {
            switch($message['data']['action']) {
                case 'speak':
                    $comms->respond($message['source'], array('response' => 'Ive slept '.$count.' times'));
                    break;
                case 'quit':
                    $running = false;
                    break;
            }
        }
    }
}
$comms->close();