I want to achieve something that might seem absurd.
I've created a PHP script that creates server socket. I'm able to connect to server socket from java client.
Now what I want is to maintain this socket at server side somewhere so that I can access it later on when needed.
But, the problem here is, as soon as the respond() function terminates, the socket is closed, and the br.readLine() method in Run class receives blank line.
For my purpose, the readLine() method should continue waiting for a response.
What I've done so far...
regsock.php (Where registering of socket should happen)
<?php
set_time_limit(0);
$fh = fopen("reg.txt", "w");
fwrite($fh, "SERVER Starting
");
$sersock = socket_create_listen(1234);
fwrite($fh, "SERVER Running
");
while(true){
respond();
}
function respond(){
global $sersock, $fh;
$sock = socket_accept($sersock);
fwrite($fh, "Client Connected
");
echo "Client: ".socket_read($sock, 1024);
socket_write($sock, "OK
");
//Some way to store client sockets?
}
socket_close($sersock);
fclose($fh);
?>
Run.java
Socket socket = new Socket("localhost", 1234);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
bw.write("Server OK?");
bw.flush();
System.out.println("Server:"+br.readLine()); //Output-> Server:OK
System.out.println("Server:"+br.readLine()); //Output-> Server:
bw.close();
br.close();
socket.close();
And, remote.php (Where I want to access the socket accepted on resgsock.php)
<?php
$sock = //Retrieve socket resource here
fwrite($sock, "REMOTE PAGE
");
echo "Socket write complete";
?>
Is it even possible or I'm just doing everything wrong.
Can this be done through some other method.
The socket accepted in regsock.php can be passed to remote.php only if remote.php is executed in the same process as regsock, or in a subprocess.
For example you could do this:
# In global setup: handle child process termination automatically
# Might break calls to "system" though
pcntl_signal(SIGCHLD, SIG_IGN);
function respond(){
global $sersock, $fh;
$sock = socket_accept($sersock);
fwrite($fh, "Client Connected
");
echo "Client: ".socket_read($sock, 1024);
socket_write($sock, "OK
");
$pid = pcntl_fork();
if ($pid == 0) {
# This is now a subprocess. If I "include" remote.php
# it can operate on $sock as if it was its own.
include "remote.php";
# Now exit the subprocess
exit;
} elsif ($pid < 0) {
# fork failed, handle error
} else {
echo "Subprocess running with pid $pid!";
# Close the copy of the socket in parent process,
# subprocess has a copy of its own.
socket_close($sock);
}
}