Browse DevX
Sign up for e-mail newsletters from DevX


Cross the Gap Between PHP and Java : Page 2

Using sophisticated application frameworks to build your network server applications is fine, but sometimes these frameworks are overkill. With a little communications programming between PHP and Java, you can establish an extensible layer that handles the annoying details of creating a custom network protocol.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 hidden—in this case, in the PHP class MapConnection, which is implemented in a file called MapConnection, in the file mapstream.PHP (see Listing 6).

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date