Skip to content

Commit

Permalink
Added examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Encritary committed May 16, 2020
1 parent 1061c9e commit 5aa92e0
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
29 changes: 29 additions & 0 deletions examples/hello-world.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

// Windows doesn't support UNIX sockets
$domain = strtolower(substr(PHP_OS, 0, 3)) === "win" ? STREAM_PF_INET : STREAM_PF_UNIX;

// Create a pair of IPC stream sockets
$streams = stream_socket_pair($domain, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);

if($streams === false or stream_set_blocking($streams[0], false) === false or stream_set_blocking($streams[1], false) === false){
die("failed to open stream socket pair");
}

// Create a pair of FD streams to access IPC sockets
$fdstreams = [];
$fdstreams[0] = fopen("php://fd/" . streamfd($streams[0]), "r+");
$fdstreams[1] = fopen("php://fd/" . streamfd($streams[1]), "r+");

if($fdstreams[0] === false or $fdstreams[1] === false or stream_set_blocking($fdstreams[0], false) === false or stream_set_blocking($fdstreams[1], false) === false){
die("failed to open fd stream pair")
}

// Write "hello" to the first and "world" to the second IPC socket
fwrite($fdstreams[0], "hello");
fwrite($fdstreams[1], "world");

// Now read directly from sockets
echo fread($streams[1], 5) . " " . fread($streams[0], 5) . PHP_EOL;
30 changes: 30 additions & 0 deletions examples/parallel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

// This example shows how you can share sockets between threads using FD.
// The extension used in this example: https://github.com/krakjoe/parallel

if(!extension_loaded("parallel"){
die("This example requires the Parallel extension");
}

if(socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $pair) === false){
die("Couldn't create socket pair");
}

// Create a runtime and run the task
$runtime = new parallel\Runtime();
$future = $runtime->run(function(int $fd) : void{
$socket = socket_import_stream(fopen("php://fd/$fd", "r+"));

// strlen("hello world") === 11
echo socket_read($socket, 11) . PHP_EOL;
}, [streamfd(socket_export_stream($pair[0]))]); // Share the first socket of the pair


// Write "hello world" to the second socket of the pair
socket_write($pair[1], "hello world", 11);

// Wait for task to complete
$future->value();

0 comments on commit 5aa92e0

Please sign in to comment.