Java has very good execution performance, and PHP has an efficient, low-cost development and deployment capabilities, so many predecessors have done a lot of integration of Java and PHP attempts, among the best of resin Quercus, and PHP-FPM communication framework jfastcgi, However, both are running on the HTTP server (where Quercus runs PHP for high performance, but also for the silver), if we need a direct and php-fpm communication, and do not want to relate to HTTP server, For example, a long-connected web game based on the socket, using PHP to implement the game logic, Java to develop a request to accept the socket client and forward the request to PHP's middle tier, that with jfastcgi or Quercus is a little powerless.
This time work relatively idle, so took some time to study the FASTCGI protocol, read the jfastcgi source code, wrote fcgi4j this small tool library.
The tool library's jar package and source code can be downloaded from the http://code.google.com/p/fcgi4j/, and you are welcome to shoot bricks or modify and reuse them.
Here is the code to implement a PHP-FPM complete request with fcgi4j:
Create FastCGI connection Fcgiconnection connection = Fcgiconnection.open (); connection. Connect (new Inetsocketaddress ("127.0.0.1", 9000)); Connection.beginrequest ("fcgi.ph P "); Set the HTTP method,get for default Connection.setrequestmethod ("Post"); Set the queryString, not required when no queryString connection.setquerystring ("Text=hello") ; Add Fcgiparams connection.addparams ("Document_root", "/var/www"); byte [] postdata = "Hello=world". GetBytes (); Set ContentLength, it ' s importent connection.setcontentlength (postdata.length); Connection.write (BYTEBUFFER.WR AP (postdata)); Print response Headers Map < string, string > responseheaders = Connection.getresp Onseheaders (); for (String key:responseHeaders.keYset ()) {System.out.println ("HTTP HEADER:" + key + "+" + resp Onseheaders.get (key));} Read response data Bytebuffer buffer = bytebuffer.allocate (10240); connection.read (buffer); buf Fer.flip (); byte [] data = new byte [Buffer.remaining ()];buffer.get (data); System.out.println (new String (data)); Close the connection connection.close ();