Using Java to connect to php-fpm java has excellent execution performance, while php has efficient and low-cost development and deployment capabilities, therefore, many predecessors have made a lot of attempts to integrate Java and PHP, among which the leader is querus of Resin and jfastcgi, a framework for communication with php-fpm, however, both of them are running on the http server (in which quercuz wants to run PHP to achieve high performance, but it is worth some money). if we need a direct communication with php-fpm, I don't want to talk to the http server. for example, I want to create a web game based on a Socket-based persistent connection and use PHP to implement the game logic, java is used to develop an intermediate layer that accepts Socket client requests and forwards the requests to php. Therefore, jfastcgi or Quercus is useless.
This time it was relatively idle, so it took some time to study the FastCGI protocol, read the source code of jfastcgi, and write the Tool Library fcgi4j.
The jar package and source code of this tool library can be downloaded from http://code.google.com/p/fcgi4j/. you can click here to modify and reuse it.
The following code uses fcgi4j to implement a complete php-fpm request:
// create FastCGI connection FCGIConnection connection = FCGIConnection.open();connection.connect( new InetSocketAddress( " 127.0.0.1 " , 9000 ));connection.beginRequest( " fcgi.php " ); // 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.wrap(postData)); // print response headers Map < String, String > responseHeaders = connection.getResponseHeaders(); for (String key : responseHeaders.keySet()){ System.out.println( " HTTP HEADER: " + key + " -> " + responseHeaders.get(key));} // read response data ByteBuffer buffer = ByteBuffer.allocate( 10240 );connection.read(buffer);buffer.flip(); byte [] data = new byte [buffer.remaining()];buffer.get(data);System.out.println( new String(data)); // close the connection connection.close();