This chapter will present how to get started with Grizzly 2.2.10, both client and server side.
First, it is necessary to depend on the correct Grizzly 2.2.10 core artifact. Maven developers will need to add following dependency to the pom:
<dependency> <groupId>org.glassfish.grizzly</groupId> <artifactId>grizzly-framework</artifactId> <version>2.2.10</version> </dependency>
Maven repository to be used is
<repository> <id>glassfish-maven2-repository.dev.java.net</id> <name>Java.net Maven 2 Repository for GlassFish</name> <url>https://maven.java.net/content/repositories/releases/</url> </repository>
Let's implement simple Echo client-server application. The client will get user's data from standard input, send data to Echo server and redirect server's response to the standard output. The responsibility of the Echo server is to read data from network channel and echo the same data back to the channel.
First of all let's implement echo filter, which will echo the received message (despite its type) back to the Grizzly Connection.
1 import java.io.IOException; 2 import org.glassfish.grizzly.filterchain.BaseFilter; 3 import org.glassfish.grizzly.filterchain.FilterChain; 4 import org.glassfish.grizzly.filterchain.FilterChainContext; 5 import org.glassfish.grizzly.filterchain.NextAction; 6 7 /** 8 * Implementation of {@link FilterChain} filter, which replies with the request 9 * message. 10 */ 11 public class EchoFilter extends BaseFilter { 12 13 /** 14 * Handle just read operation, when some message has come and ready to be 15 * processed. 16 * 17 * @param ctx Context of {@link FilterChainContext} processing 18 * @return the next action 19 * @throws java.io.IOException 20 */ 21 @Override 22 public NextAction handleRead(FilterChainContext ctx) 23 throws IOException { 24 // Peer address is used for non-connected UDP Connection :) 25 final Object peerAddress = ctx.getAddress(); 26 27 final Object message = ctx.getMessage(); 28 29 ctx.write(peerAddress, message, null); 30 31 return ctx.getStopAction(); 32 } 33 }
All the server FilterChain bricks are ready - let's initialize and start the server.
1 import java.io.IOException; 2 import java.nio.charset.Charset; 3 import java.util.logging.Logger; 4 import org.glassfish.grizzly.filterchain.FilterChainBuilder; 5 import org.glassfish.grizzly.filterchain.TransportFilter; 6 import org.glassfish.grizzly.nio.transport.TCPNIOTransport; 7 import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; 8 import org.glassfish.grizzly.utils.StringFilter; 9 10 /** 11 * Class initializes and starts the echo server, based on Grizzly 2.2.10 12 */ 13 public class EchoServer { 14 private static final Logger logger = Logger.getLogger(EchoServer.class.getName()); 15 16 public static final String HOST = "localhost"; 17 public static final int PORT = 7777; 18 19 public static void main(String[] args) throws IOException { 20 // Create a FilterChain using FilterChainBuilder 21 FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless(); 22 23 // Add TransportFilter, which is responsible 24 // for reading and writing data to the connection 25 filterChainBuilder.add(new TransportFilter()); 26 27 // StringFilter is responsible for Buffer <-> String conversion 28 filterChainBuilder.add(new StringFilter(Charset.forName("UTF-8"))); 29 30 // EchoFilter is responsible for echoing received messages 31 filterChainBuilder.add(new EchoFilter()); 32 33 // Create TCP transport 34 final TCPNIOTransport transport = 35 TCPNIOTransportBuilder.newInstance().build(); 36 37 transport.setProcessor(filterChainBuilder.build()); 38 try { 39 // binding transport to start listen on certain host and port 40 transport.bind(HOST, PORT); 41 42 // start the transport 43 transport.start(); 44 45 logger.info("Press any key to stop the server..."); 46 System.in.read(); 47 } finally { 48 logger.info("Stopping transport..."); 49 // stop the transport 50 transport.stop(); 51 52 logger.info("Stopped transport..."); 53 } 54 } 55 }
Client filter is responsible for redirecting server response to the standard output. Please note, the ClientFilter requires FilterChainContext messages to be java.lang.String (line 21), so it relies StringFilter is preceding it in the FilterChain.
1 import java.io.IOException; 2 import org.glassfish.grizzly.filterchain.BaseFilter; 3 import org.glassfish.grizzly.filterchain.FilterChainContext; 4 import org.glassfish.grizzly.filterchain.NextAction; 5 6 /** 7 * Client filter is responsible for redirecting server response to the standard output 8 */ 9 public class ClientFilter extends BaseFilter { 10 /** 11 * Handle just read operation, when some message has come and ready to be 12 * processed. 13 * 14 * @param ctx Context of {@link FilterChainContext} processing 15 * @return the next action 16 * @throws java.io.IOException 17 */ 18 @Override 19 public NextAction handleRead(final FilterChainContext ctx) throws IOException { 20 // We get String message from the context, because we rely prev. Filter in chain is StringFilter 21 final String serverResponse = ctx.getMessage(); 22 System.out.println("Server echo: " + serverResponse); 23 24 return ctx.getStopAction(); 25 } 26 }
Now we're ready to initialize the client, which includes FilterChain and Transport initialization
1 Connection connection = null; 2 3 // Create a FilterChain using FilterChainBuilder 4 FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless(); 5 6 // Add TransportFilter, which is responsible 7 // for reading and writing data to the connection 8 filterChainBuilder.add(new TransportFilter()); 9 10 // StringFilter is responsible for Buffer <-> String conversion 11 filterChainBuilder.add(new StringFilter(Charset.forName("UTF-8"))); 12 13 // ClientFilter is responsible for redirecting server responses to the standard output 14 filterChainBuilder.add(new ClientFilter()); 15 16 // Create TCP transport 17 final TCPNIOTransport transport = 18 TCPNIOTransportBuilder.newInstance().build(); 19 transport.setProcessor(filterChainBuilder.build());
Let's complete the code above by adding the logic, which reads user data from the standard input, sends it to the server and client shutdown being executed on end of input.
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.nio.charset.Charset; 5 import java.util.logging.Logger; 6 import java.util.concurrent.ExecutionException; 7 import java.util.concurrent.Future; 8 import java.util.concurrent.TimeUnit; 9 import java.util.concurrent.TimeoutException; 10 import org.glassfish.grizzly.Connection; 11 import org.glassfish.grizzly.Grizzly; 12 import org.glassfish.grizzly.filterchain.FilterChainBuilder; 13 import org.glassfish.grizzly.filterchain.TransportFilter; 14 import org.glassfish.grizzly.nio.transport.TCPNIOTransport; 15 import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; 16 import org.glassfish.grizzly.utils.StringFilter; 17 18 /** 19 * The simple client, which sends a message to the echo server 20 * and waits for response 21 */ 22 public class EchoClient { 23 private static final Logger logger = Grizzly.logger(EchoClient.class); 24 25 public static void main(String[] args) throws IOException, 26 ExecutionException, InterruptedException, TimeoutException { 27 28 Connection connection = null; 29 30 // Create a FilterChain using FilterChainBuilder 31 FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless(); 32 // Add TransportFilter, which is responsible 33 // for reading and writing data to the connection 34 filterChainBuilder.add(new TransportFilter()); 35 // StringFilter is responsible for Buffer <-> String conversion 36 filterChainBuilder.add(new StringFilter(Charset.forName("UTF-8"))); 37 // ClientFilter is responsible for redirecting server responses to the standard output 38 filterChainBuilder.add(new ClientFilter()); 39 40 // Create TCP transport 41 final TCPNIOTransport transport = 42 TCPNIOTransportBuilder.newInstance().build(); 43 transport.setProcessor(filterChainBuilder.build()); 44 45 try { 46 // start the transport 47 transport.start(); 48 49 // perform async. connect to the server 50 Future<Connection> future = transport.connect(EchoServer.HOST, 51 EchoServer.PORT); 52 // wait for connect operation to complete 53 connection = future.get(10, TimeUnit.SECONDS); 54 55 assert connection != null; 56 57 System.out.println("Ready... (\"q\" to exit)"); 58 final BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); 59 do { 60 final String userInput = inReader.readLine(); 61 if (userInput == null || "q".equals(userInput)) { 62 break; 63 } 64 65 connection.write(userInput); 66 } while (true); 67 } finally { 68 // close the client connection 69 if (connection != null) { 70 connection.close(); 71 } 72 73 // stop the transport 74 transport.stop(); 75 } 76 } 77 }
EchoClient could be run easily using command line like
java -classpath grizzly-framework.jar EchoClient
or your favorite IDE.
By default, if standard input and outtput were not changed - you'll see the following on the console:
Ready... ("q" to exit)
Now the client is ready for your input. Each time you typed a line and pressed <ENTER> - the line will be sent to the server and response got:
Ready... ("q" to exit) Hey there! Server echo: Hey there!