PHP Socket Java message exchange
I'm trying to make a communication between a PHP page and running Java server. Just a simple string exchange through sockets.
This is my Java Code for thread that handles the connection:
InputStream in = clientSocket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String request;
if((request=br.readLine())!=null){
System.out.println("got the following request: " + request);
out.write(request +"\n");
out.flush();
out.close();
in.close();
}
I tested it with simple Java cl开发者_Go百科ient that sends the string then receives the result and prints it back and it worked. Both client and the server had the same output.
This is my PHP code:
$fp = @fsockopen ($host, $port, $errno, $errstr);
if($fp){
fputs($fp, $str);
//echo fgets($fp);
}
close($fp);
Which sends the string to the Server, and the Server receives it. But once I uncomment the line with fgets($fp) I am blocked until some sort of timeout happens after 1-2 minutes. During that Block my server is not receiving anything. After timeout my server prints, that it has received the line, and probably sends the response back, however, the PHP code doesn't print anything.
What could be the problem?
Thank you in advance.
P.S. It is probably worth saying that I am accessing this web page through AJAX, so it "echoes" the result back to the other page.
I prefer the socket_*
functions, personally. But either way, you're likely missing checking for a terminating character:
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($sock, $host, $port);
socket_write($sock, $str);
$response = '';
while($resp = socket_read($sock, 1024)) {
if(!$resp)
break;
$response .= $resp;
if(strpos($resp, "\n") !== false)
break;
}
echo "Server said: {$response}";
Try adding after fsockopen()
:
stream_set_blocking($fp,0);
$info=stream_get_meta_data($fp);
if ($fp) {
fputs($fp,$str);
$reply=''.
while (!feof($fp) && !$info['timed_out']) {
$reply.=fgets($fp);
echo $reply;
}
close($fp);
My friend sent me this link http://abejali.com/?p=56 with a very nice code that does the trick. There is a trick inside that solves the problem
The following code works. The trick was to add chr(13) . chr(10) to the end of the string.
$str.= chr(13) . chr(10);
stream_set_blocking($fp,0);
$info=stream_get_meta_data($fp);
if ($fp) {
fputs($fp,$str);
$reply='';
while (!feof($fp) && !$info['timed_out']) {
$reply.= fread($fp, 1);
}
echo $reply;
}
精彩评论