The Java Portion
Using the following code, the example Java server takes two numbers, adds them, and sends the sum back to the user:
public Map transform( Map map ) {
// Get the two addends from the input packet.
int i0 = ((Integer)map.get( "addend0" )).intValue();
int i1 = ((Integer)map.get( "addend1" )).intValue();
// Add them, producing a sum.
int sum = i0+i1;
// Build an ouptut packet.
Map answer = new HashMap();
answer.put( "sum", new Integer( sum ) );
return answer;
}
This code lives in a class called AdditionServer (see Listing 2), which inherits from a base class called Server (see Listing 1). Server takes care of the details involved with reading the input packet from the TCP/IP stream and writing the answer to the output TCP/IP stream.
With these details addressed, creating a new service and running it inside a Java server is very easy. All you have to do is inherit from Server and implement a method called transform(), which takes an input packet and turns it into an output packet.
The PHP Portion
In order for the PHP code to connect to the Java server, it must speak TCP/IP. Luckily, PHP has full support for TCP/IP. The following PHP code sends two numbers to the addition server (see Listing 7), which adds them and sends them back:
// Make a connection to the Java server.
$mc = new MapConnection( "localhost", 5000 );
// Build a packet containing the two numbers.
$problem = array( "addend0"=>100, "addend1"=>44 );
// Send the packet to the server.
$mc->write( $problem );
// Get the sum from the server.
$answer = $mc->read();
$sum = $answer["sum"];
Again, the communication details are hiddenin this case, in the PHP class MapConnection, which is implemented in a file called MapConnection, in the file mapstream.PHP (see Listing 6).