Skip to content
Richard T. Miles edited this page Aug 28, 2017 · 3 revisions

In order to run applications over a WebSocket written in PHP you'll need to be using the (CLI) compiler. To find out what PHP version your command line interface defaults to use php -v

If your compiler defaulted to something like PHP-fastcgi, ect. you'll need to find in on your system. In my particular build I .... have to head to class, finish this later

websocketd --port=8080 --devconsole /home/urs/public_html/Socket.php

Socket.php

#!/usr/local/bin/php
<?php declare(ticks = 1);

# https://www.leaseweb.com/labs/2013/08/catching-signals-in-php-scripts/
pcntl_signal(SIGTERM, 'signalHandler'); // Termination ('kill' was called')
pcntl_signal(SIGHUP, 'signalHandler');  // Terminal log-out
pcntl_signal(SIGINT, 'signalHandler');  // Interrupted ( Ctrl-C is pressed)

$fifoPath = __DIR__ . '/1.fifo';

print $fifoPath;

if (!file_exists( $fifoPath )) posix_mkfifo( $fifoPath, 0600 );

if (pcntl_fork() == 0)
{   // child
    $file = fopen($fifoPath,"w");
    sleep(1);
    exit(0);
} else {
    $fifoFile = fopen( $fifoPath, 'r' );
}
$stdin = fopen('php://stdin', 'r');

echo "COMMUNICATION STARTED\n PID :: " . getmypid() . "\n\n";

while(true) {
    sleep( 1 );
    $readers = array($fifoFile, $stdin);
    if (($stream = stream_select( $readers, $writers, $except, 0, 15 )) === false) {
        print "A stream error occurred\n";
        break;
    } else {
        foreach ($readers as $input => $fd) {
            if ($fd == $stdin) {
                $line = fgets($stdin); // I think were going to make this a search function
                // TODO - search in app
                print "You sent :: $line \n";
            } elseif ($fd == $fifoFile) {
                $data = fread( $fifoFile, $bytes = 124 );
                if (!empty( $data )) print "App Sent :: " . $data . "\n";
            }
        }
    }
}

function signalHandler($signal) {
    print "Signal :: $signal\n";
    global $fifoPath, $fp;
    @fclose($fp);
    @unlink($fifoPath);
    print "Safe Exit \n\n";
    exit(1);
}

Application Communication (think event handling)

communication.php

#!/usr/local/bin/php
<?php
/**
 * Created by IntelliJ IDEA.
 * User: Miles
 * Date: 8/27/17
 * Time: 10:00 PM
 */

$fifoPath = __DIR__ . '/1.fifo';

if (!file_exists($fifoPath)) {
    print "User not active \n\n";
    exit(0);
}

$fifo = fopen( $fifoPath, 'w' );

$data = "Richard Miles \n";
fwrite($fifo, $data, 1024);


echo "Done \n\n";
Clone this wiki locally