Hello Etch

The classic helloworld example in Etch is provided in examples/helloworld (both svn and releases, starting with 1.1).

You will find the following directory structure:

  • build.xml
  • README.txt
  • src
    • main
      • csharp (csharp implementation)
      • java (java implementation)
      • c (c implementation)
      • etch
        • HelloWorld.etch (NSDL service description)
    • target (created on build, contains generated parts)

You can build the HelloWorld example (generate source from HelloWorld.etch, compile and test) for Java and CSharp on the command line using

cd examples/helloworld
ant Debug

Note that you must setup your command line environment correctly. If you have checked out the trunk from svn, use scripts/antSetup.bat and the information in Building Trunk.

HelloWorld NSDL

module org.apache.etch.examples.helloworld

service HelloWorld {
	struct user (
		int id,
		string name
	)

	exception UserUnknownException (
		string mes
	)

	@Direction(Server)
	string say_hello(user to_whom) throws UserUnknownException

}

The service provides the say_hello method, which should greet a user, which is supplied as a parameter.

Java HelloWorld in more detail

The implementation of the example server and client is located in:

trunk\examples\helloworld\src\main\java\org\apache\etch\examples\helloworld\

The classes MainHelloWorldListener and MainHelloWorldClient spawn the server and client parts of the helloworld example.

The Client code is:

String uri = "tcp://127.0.0.1:4001";
RemoteHelloWorldServer server = HelloWorldHelper.newServer( uri, null,new MainHelloWorldClient() );
server._startAndWaitUp( 4000 );
user u = new user(5, "Testuser");
System.out.println(server.say_hello(u));
server._stopAndWaitDown( 4000 );

It connects to an Etch server running on localhost by constructing a new RemoteHelloWorldServer object (the proxy in the rpc sense) using the HelloWorldHelper class, which is generated from the NSDL. Afterwards the connection is started and the say_hello method is called.

Starting a server is also quite simple:

String uri = "tcp://127.0.0.1:4001";
ServerFactory listener = HelloWorldHelper.newListener( uri, null, new MainHelloWorldListener() );
listener.transportControl( Transport.START_AND_WAIT_UP, 4000 );

The last parameter of newListener must implement the HelloWorldServerFactory interface, which defines the newHelloWorldServer factory method. This method is called by the etch runtime once for every client connect and must return an instance of ImplHelloWorldServer, which is the implementation class for the services that are invoked for that specific connected client. In the code for the client above you can see the same principle for the client. This already shows Etch's basic principle of two-way communication: The Client has an Impl... object, too. It contains all @Direction(client) methods from the IDL (in this small example, there are none. see the chat example for client-side methods.)