The Echo program consists of two parts:
import java.util.logging.Level; import java.util.logging.Logger; import de.netseeker.ejoe.handler.ServerHandler; public class EchoHandler implements ServerHandler { public Object handle( Object obj ) throws Exception { //the cast is just build in to ensure that we've got a String and not another object type String msg = (String)obj; logger.log( Level.INFO, "Received client message: " + msg); return msg; } }
import java.util.logging.Level; import java.util.logging.Logger; import java.io.IOException; import de.netseeker.ejoe.EJServer; public class EchoServer { private static final Logger logger = Logger.getLogger( EchoServer.class.getName() ); public static void main( String[] args ) { EJServer server = new EJServer( new EchoHandler(), 9999 ); try { server.start(); } catch (IOException e) { logger.log(Level.SEVERE, "Exception while starting server!", e); } } }
Our client will have to read input from the user on the standard input stream, and then forwards that text to the Echo server by passing the input to an EJClient instance. The client program reads and displays the data passed back to it from the server:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import de.netseeker.ejoe.EJClient; import de.netseeker.ejoe.adapter.UTF8StringAdapter; public class EchoClient { public static void main( String[] args ) { //create a new instance of EJClient, tell it to use localhost as EJOE server on port 9999 //and use the simple UTF8 based string (de)serializer EJClient client = new EJClient( "localhost", 9999, new UTF8StringAdapter() ); //request a persistent connection to the EJOE server client.enablePersistentConnection( true ); try { BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); String str = "", result = null; System.out.print( "> type \"exit\" to quit the client program." ); while (str != null) { System.out.print( "> type your message: " ); //read input from the commandline str = in.readLine(); if( str.equalsIgnoreCase("exit")) { System.out.println("Bye." ); client.close(); System.exit(1); } //user typed a message if( str.length() > 0 ) { //invoke EJClient to handle the request result = (String)client.execute( str ); System.out.println("Server returned: " + result ); } } } catch (IOException e) { e.printStackTrace(); } } }
As you can see in the three example sources above, it is an easy task to implement a network client/server solution with EJOE.
Well, an Echo server isn't really a hard exercise but it shows the basic usage pattern when creating a network solution based
on EJOE.
To understand what EJOE does for you, just recognize what the things are we don't see in the example sources above: