Last active
August 29, 2015 14:06
-
-
Save eridal/b53dabf1589e382d95d6 to your computer and use it in GitHub Desktop.
PHP to Java persistent process comunication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Java { | |
public static void main(String[] args) { | |
Scanner s = new Scanner(System.in); | |
while (s.hasNextInt()) { // <-- blocking read | |
int i = s.nextInt(); | |
System.out.print(i + 1); // <-- send it back | |
System.out.print('\n'); | |
System.out.flush(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo 'Compiling..', PHP_EOL; | |
system('javac Java.java'); | |
echo 'Starting JVM..', PHP_EOL; | |
$pipes = null; | |
$process = proc_open('java Java', [0 => ['pipe', 'r'], | |
1 => ['pipe', 'w']], $pipes); | |
if (!is_resource($process)) { | |
exit('ERR: Cannot create java process'); | |
} | |
list($javaIn, $javaOut) = $pipes; | |
$i = 1; | |
while (true) { | |
fwrite($javaIn, $i); // <-- send the number | |
fwrite($javaIn, PHP_EOL); | |
fflush($javaIn); | |
$reply = fgetss($javaOut); // <-- blocking read | |
$i = intval($reply); | |
echo $i, PHP_EOL; | |
sleep(1); // <-- wait 1 second | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment