[prev in list] [next in list] [prev in thread] [next in thread] 

List:       mina-commits
Subject:    svn commit: r1856368 - /mina/site/trunk/content/mina-project/userguide/ch2-basics/
From:       elecharny () apache ! org
Date:       2019-03-27 5:50:51
Message-ID: 20190327055051.B70A73A0D67 () svn01-us-west ! apache ! org
[Download RAW message or body]

Author: elecharny
Date: Wed Mar 27 05:50:51 2019
New Revision: 1856368

URL: http://svn.apache.org/viewvc?rev=1856368&view=rev
Log:
Renamed chapter 2 pages

Added:
    mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1-application-architecture.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.1-server-architecture.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.2-client-architecture.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.2-sample-tcp-server.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.3-sample-tcp-client.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.4-sample-udp-server.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.5-sample-udp-client.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.6-summary.mdtext
Removed:
    mina/site/trunk/content/mina-project/userguide/ch2-basics/application-architecture.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/client-architecture.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/sample-tcp-client.mdtext
    mina/site/trunk/content/mina-project/userguide/ch2-basics/sample-tcp-server.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/sample-udp-client.mdtext
    mina/site/trunk/content/mina-project/userguide/ch2-basics/sample-udp-server.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/server-architecture.mdtext
  mina/site/trunk/content/mina-project/userguide/ch2-basics/summary.mdtext

Added: mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1-application-architecture.mdtext
                
URL: http://svn.apache.org/viewvc/mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1-application-architecture.mdtext?rev=1856368&view=auto
 ==============================================================================
--- mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1-application-architecture.mdtext \
                (added)
+++ mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1-application-architecture.mdtext \
Wed Mar 27 05:50:51 2019 @@ -0,0 +1,64 @@
+Title: 2.1 - Application Architecture
+NavUp: ch2-basics.html
+NavUpText: Chapter 2 - Basics
+NavNext: ch2.2-sample-tcp-server.html
+NavNextText: 2.2 - Sample TCP Server
+Notice:    Licensed to the Apache Software Foundation (ASF) under one
+           or more contributor license agreements.  See the NOTICE file
+           distributed with this work for additional information
+           regarding copyright ownership.  The ASF licenses this file
+           to you under the Apache License, Version 2.0 (the
+           "License"); you may not use this file except in compliance
+           with the License.  You may obtain a copy of the License at
+           .
+             http://www.apache.org/licenses/LICENSE-2.0
+           .
+           Unless required by applicable law or agreed to in writing,
+           software distributed under the License is distributed on an
+           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+           KIND, either express or implied.  See the License for the
+           specific language governing permissions and limitations
+           under the License.
+
+* [2.1.1 - Server Architecture](ch2.2.1-server-architecture.html)
+* [2.2.2 - Client Architecture](ch2.2.2-client-architecture.html)
+
+#2.1 -  MINA based Application Architecture
+
+It's the question most asked : 'How does a **MINA** based application look like'? In \
this article lets see what's the architecture of MINA based application. Have tried \
to gather the information from presentations based on **MINA**. +
+A Bird's Eye View :
+
+![](../../../staticresources/images/mina/apparch_small.png)
+
+Here, we can see that **MINA** is the glue between your application (be it a client \
or a server) and the underlying network layer, which can be based on TCP, UDP, in-VM \
comunication or even a RS-232C serial protocol for a client. +
+You just have to design your application on top of MINA without having to handle all \
the complexity of the newtork layer. +
+Lets take a deeper dive into the details now. The following image shows a bit more \
the internal of **MINA**, and what are each of the **MINA** components doing : +
+![](../../../staticresources/images/mina/mina_app_arch.png)
+
+(The image is from Emmanuel Lécharny presentation [MINA in real life \
(ApacheCon EU 2009)](../../../staticresources/pdfs/Mina_in_real_life_ASEU-2009.pdf)) \
+ +Broadly, MINA based applications are divided into 3 layers
+
+* I/O Service - Performs actual I/O
+* I/O Filter Chain - Filters/Transforms bytes into desired Data Structures and \
vice-versa +* I/O Handler - Here resides the actual business logic
+
+So, in order to create a MINA based Application, you have to :
+
+1. Create an I/O service - Choose from already available Services (*Acceptor) or \
create your own +2. Create a Filter Chain - Choose from already existing Filters or \
create a custom Filter for transforming request/response +3. Create an I/O Handler - \
Write business logic, on handling different messages +
+This is pretty much it. 
+
+You can get a bit deeper by reading those two pages :
+
+* [2.1.1 - Server Architecture](ch2.2.1-server-architecture.html)
+* [2.2.2 - Client Architecture](ch2.2.2-client-architecture.html)
+
+Of course, **MINA** offers more than just that, and you will robably have to take \
care of many oher aspects, like the messages encoding/decoding, the network \
configuration how to scale up, etc... We will have a further look at those aspects in \
the next chapters. +

Added: mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.1-server-architecture.mdtext
                
URL: http://svn.apache.org/viewvc/mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.1-server-architecture.mdtext?rev=1856368&view=auto
 ==============================================================================
--- mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.1-server-architecture.mdtext \
                (added)
+++ mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.1-server-architecture.mdtext \
Wed Mar 27 05:50:51 2019 @@ -0,0 +1,45 @@
+Title: 2.1.1 - Server Architecture
+NavUp: ch2.1-application-architecture.html
+NavUpText: 2.1 - Application Architecture
+NavNext: ch2.1.2-client-architecture.html
+NavNextText: 2.1.2 - Client Architecture
+Notice:    Licensed to the Apache Software Foundation (ASF) under one
+           or more contributor license agreements.  See the NOTICE file
+           distributed with this work for additional information
+           regarding copyright ownership.  The ASF licenses this file
+           to you under the Apache License, Version 2.0 (the
+           "License"); you may not use this file except in compliance
+           with the License.  You may obtain a copy of the License at
+           .
+             http://www.apache.org/licenses/LICENSE-2.0
+           .
+           Unless required by applicable law or agreed to in writing,
+           software distributed under the License is distributed on an
+           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+           KIND, either express or implied.  See the License for the
+           specific language governing permissions and limitations
+           under the License.
+
+# 2.1.1 - Server Architecture
+
+We have exposed the **MINA** Application Architecture in the previous section. Let's \
now focus on the Server Architecture. Basically, a Server listens on a port for \
incoming requests, process them and send replies. It also creates and handles a \
session for each client (whenever we have a TCP or UDP based protocol), this will be \
explain more extensively in the [chapter 4](../ch4-session/ch4-session.html). +
+![](../../../staticresources/images/mina/Server_arch.png)
+
+* IOAcceptor listens on the network for incoming connections/packets
+* For a new connection, a new session is created and all subsequent request from IP \
Address/Port combination are handled in that Session +* All packets received for a \
Session, traverses the Filter Chain as specified in the diagram. Filters can be used \
to modify the content of packets (like converting to Objects, adding/removing \
information etc). For converting to/from raw bytes to High Level Objects, \
PacketEncoder/Decoder are particularly useful +* Finally the packet or converted \
object lands in `IOHandler`. `IOHandler`s can be used to fulfill business needs. +
+## Session creation
+
+Whenever a client connects on a MINA server, we will create a new session to store \
persistent data into it. Even if the protocol is not connected, this session will be \
created. The following schema shows how **MINA** handles incoming connections : +
+![Incoming connections \
handling](../../../staticresources/images/mina/incoming-connections.png) +
+
+## Incoming messages processing
+
+We will now explain how **MINA** processes incoming messages.
+
+Assuming that a session has been created, any new incoming message will result in a \
selector being waken up \ No newline at end of file

Added: mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.2-client-architecture.mdtext
                
URL: http://svn.apache.org/viewvc/mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.2-client-architecture.mdtext?rev=1856368&view=auto
 ==============================================================================
--- mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.2-client-architecture.mdtext \
                (added)
+++ mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.1.2-client-architecture.mdtext \
Wed Mar 27 05:50:51 2019 @@ -0,0 +1,34 @@
+Title: 2.1.2 - Client Architecture
+NavUp: ch2.1-application-architecture.html
+NavUpText: 2.1 - Application Architecture
+NavPrev: ch2.1.1-server-architecture.html
+NavPrevText: 2.1.1 - Server Architecture
+Notice:    Licensed to the Apache Software Foundation (ASF) under one
+           or more contributor license agreements.  See the NOTICE file
+           distributed with this work for additional information
+           regarding copyright ownership.  The ASF licenses this file
+           to you under the Apache License, Version 2.0 (the
+           "License"); you may not use this file except in compliance
+           with the License.  You may obtain a copy of the License at
+           .
+             http://www.apache.org/licenses/LICENSE-2.0
+           .
+           Unless required by applicable law or agreed to in writing,
+           software distributed under the License is distributed on an
+           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+           KIND, either express or implied.  See the License for the
+           specific language governing permissions and limitations
+           under the License.
+
+
+# 2.1.2 - Client Architecture
+
+
+We had a brief look at MINA based Server Architecture, lets see how Client looks \
like. Clients need to connect to a Server, send message and process the responses. +
+![](../../../staticresources/images/mina/clientdiagram.png)
+
+* Client first creates an IOConnector (MINA Construct for connecting to Socket), \
initiates a bind with Server +* Upon Connection creation, a Session is created and is \
associated with Connection +* Application/Client writes to the Session, resulting in \
data being sent to Server, after traversing the Filter Chain +* All the \
responses/messages received from Server are traverses the Filter Chain and lands at \
IOHandler, for processing

Added: mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.2-sample-tcp-server.mdtext
                
URL: http://svn.apache.org/viewvc/mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.2-sample-tcp-server.mdtext?rev=1856368&view=auto
 ==============================================================================
--- mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.2-sample-tcp-server.mdtext \
                (added)
+++ mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.2-sample-tcp-server.mdtext \
Wed Mar 27 05:50:51 2019 @@ -0,0 +1,244 @@
+Title: 2.2 - Sample TCP Server
+NavUp: ch2-basics.html
+NavUpText: Chapter 2 - Basics
+NavPrev: ch2.1-application-architecture.html
+NavPrevText: 2.1 - Application Architecture
+NavNext: ch2.3-sample-tcp-client.html
+NavNextText: 2.3 - Sample TCP Client
+Notice:    Licensed to the Apache Software Foundation (ASF) under one
+           or more contributor license agreements.  See the NOTICE file
+           distributed with this work for additional information
+           regarding copyright ownership.  The ASF licenses this file
+           to you under the Apache License, Version 2.0 (the
+           "License"); you may not use this file except in compliance
+           with the License.  You may obtain a copy of the License at
+           .
+             http://www.apache.org/licenses/LICENSE-2.0
+           .
+           Unless required by applicable law or agreed to in writing,
+           software distributed under the License is distributed on an
+           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+           KIND, either express or implied.  See the License for the
+           specific language governing permissions and limitations
+           under the License.
+
+# 2.2 - Sample TCP Server
+
+This tutorial will walk you through the process of building a MINA based program.  \
This tutorial will walk through building a time server.  The following prerequisites \
are required for this tutorial: +
+* MINA 2.x Core
+* JDK 1.5 or greater
+* SLF4J 1.3.0 or greater
+    * __Log4J 1.2__ users: slf4j-api.jar, slf4j-log4j12.jar, and \
[Log4J](http://logging.apache.org/log4j/1.2/) 1.2.x +    * __Log4J 1.3__ users: \
slf4j-api.jar, slf4j-log4j13.jar, and [Log4J](http://logging.apache.org/log4j/1.2/) \
1.3.x +    * __java.util.logging__ users: slf4j-api.jar and slf4j-jdk14.jar
+    * __IMPORTANT__: Please make sure you are using the right slf4j-*.jar that \
matches to your logging framework. +
+For instance, slf4j-log4j12.jar and log4j-1.3.x.jar can not be used together, and \
will malfunction. +
+We have tested this program on both Windows© 2000 professional and linux.  If \
you have any problems getting this program to work, please do not hesitate to \
[contact us](../../../contact.html) in order to talk to the MINA developers.  Also, \
this tutorial has tried to remain independent of development environments (IDE, \
editors..etc).  This tutorial will work with any environment that you are comfortable \
with.  Compilation commands and steps to execute the program have been removed for \
brevity.  If you need help learning how to either compile or execute java programs, \
please consult the [Java tutorial](http://java.sun.com/docs/books/tutorial/). +
+## Writing the MINA time server 
+
+We will begin by creating a file called MinaTimeServer.java. The initial code can be \
found below: +
+	:::java
+	public class MinaTimeServer {
+		public static void main(String[] args) {
+			// code will go here next
+		}
+	}
+
+This code should be straightforward to all.  We are simply defining a main method \
that will be used to kick off the program.  At this point, we will begin to add the \
code that will make up our server.  First off, we need an object that will be used to \
listen for incoming connections.  Since this program will be TCP/IP based, we will \
add a SocketAcceptor to our program. +
+	:::java
+	import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
+	
+	public class MinaTimeServer
+	{
+		public static void main( String[] args )
+		{
+			IoAcceptor acceptor = new NioSocketAcceptor();
+		}
+	}
+
+With the NioSocketAcceptor class in place, we can go ahead and define the handler \
class and bind the NioSocketAcceptor to a port : +
+	:::java
+	import java.net.InetSocketAddress;
+	
+	import org.apache.mina.core.service.IoAcceptor;
+	import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
+	
+	public class MinaTimeServer
+	{
+		private static final int PORT = 9123;
+		public static void main( String[] args ) throws IOException
+		{
+			IoAcceptor acceptor = new NioSocketAcceptor();
+			acceptor.bind( new InetSocketAddress(PORT) );
+		}
+	}
+
+As you see, there is a call to acceptor.setLocalAddress( new InetSocketAddress(PORT) \
);. This method defines what host and port this server will listen on. The final \
method is a call to IoAcceptor.bind(). This method will bind to the specified port \
and start processing of remote clients. +
+Next we add a filter to the configuration. This filter will log all information such \
as newly created sessions, messages received, messages sent, session closed. The next \
filter is a ProtocolCodecFilter. This filter will translate binary or protocol \
specific data into message object and vice versa. We use an existing TextLine factory \
because it will handle text base message for you (you don't have to write the codec \
part) +
+	:::java
+	import java.io.IOException;
+	import java.net.InetSocketAddress;
+	import java.nio.charset.Charset;
+	
+	import org.apache.mina.core.service.IoAcceptor;
+	import org.apache.mina.filter.codec.ProtocolCodecFilter;
+	import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
+	import org.apache.mina.filter.logging.LoggingFilter;
+	import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
+	
+	public class MinaTimeServer
+	{
+		public static void main( String[] args )
+		{
+			IoAcceptor acceptor = new NioSocketAcceptor();
+			acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
+			acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new \
TextLineCodecFactory( Charset.forName( "UTF-8" )))); +			acceptor.bind( new \
InetSocketAddress(PORT) ); +		}
+	}
+
+At this point, we will define the handler that will be used to service client \
connections and the requests for the current time. The handler class is a class that \
must implement the interface IoHandler. For almost all programs that use MINA, this \
becomes the workhorse of the program, as it services all incoming requests from the \
clients. For this tutorial, we will extend the class IoHandlerAdapter. This is a \
class that follows the [adapter design \
pattern](http://en.wikipedia.org/wiki/Adapter_pattern) which simplifies the amount of \
code that needs to be written in order to satisfy the requirement of passing in a \
class that implements the IoHandler interface. +
+	:::java
+	import java.net.InetSocketAddress;
+	import java.nio.charset.Charset;
+	
+	import org.apache.mina.core.service.IoAcceptor;
+	import org.apache.mina.filter.codec.ProtocolCodecFilter;
+	import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
+	import org.apache.mina.filter.logging.LoggingFilter;
+	import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
+	
+	public class MinaTimeServer
+	{
+		public static void main( String[] args ) throws IOException
+		{
+			IoAcceptor acceptor = new NioSocketAcceptor();
+			acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
+			acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new \
TextLineCodecFactory( Charset.forName( "UTF-8" )))); +			acceptor.setHandler(  new \
TimeServerHandler() ); +			acceptor.bind( new InetSocketAddress(PORT) );
+		}
+	}
+
+We will now add in the NioSocketAcceptor configuration. This will allow us to make \
socket-specific settings for the socket that will be used to accept connections from \
clients. +
+	:::java
+	import java.net.InetSocketAddress;
+	import java.nio.charset.Charset;
+	
+	import org.apache.mina.core.session.IdleStatus;
+	import org.apache.mina.core.service.IoAcceptor;
+	import org.apache.mina.filter.codec.ProtocolCodecFilter;
+	import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
+	import org.apache.mina.filter.logging.LoggingFilter;
+	import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
+	
+	public class MinaTimeServer
+	{
+		public static void main( String[] args ) throws IOException
+		{
+        	IoAcceptor acceptor = new NioSocketAcceptor();
+			acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
+			acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new \
TextLineCodecFactory( Charset.forName( "UTF-8" )))); +			acceptor.setHandler(  new \
TimeServerHandler() ); +			acceptor.getSessionConfig().setReadBufferSize( 2048 );
+			acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
+			acceptor.bind( new InetSocketAddress(PORT) );
+		}
+	}
+
+There are 2 new lines in the MinaTimeServer class. These methods set the set the \
IoHandler, input buffer size and the idle property for the sessions. The buffer size \
will be specified in order to tell the underlying operating system how much room to \
allocate for incoming data. The second line will specify when to check for idle \
sessions. In the call to setIdleTime, the first parameter defines what actions to \
check for when determining if a session is idle, the second parameter defines the \
length of time in seconds that must occur before a session is deemed to be idle. +
+The code for the handler is shown below:
+
+	:::java
+	import java.util.Date;
+	
+	import org.apache.mina.core.session.IdleStatus;
+	import org.apache.mina.core.service.IoHandlerAdapter;
+	import org.apache.mina.core.session.IoSession;
+	
+	public class TimeServerHandler extends IoHandlerAdapter
+	{
+		@Override
+		public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
+		{
+			cause.printStackTrace();
+		}
+		@Override
+		public void messageReceived( IoSession session, Object message ) throws Exception
+		{
+			String str = message.toString();
+			if( str.trim().equalsIgnoreCase("quit") ) {
+            	session.close();
+				return;
+        	}
+			Date date = new Date();
+			session.write( date.toString() );
+			System.out.println("Message written...");
+		}
+		@Override
+		public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
+		{
+        	System.out.println( "IDLE " + session.getIdleCount( status ));
+		}
+	}
+
+The methods used in this class are exceptionCaught, messageReceived and sessionIdle. \
exceptionCaught should always be defined in a handler to process and exceptions that \
are raised in the normal course of handling remote connections. If this method is not \
defined, exceptions may not get properly reported. +
+The exceptionCaught method will simply print the stack trace of the error and close \
the session. For most programs, this will be standard practice unless the handler can \
recover from the exception condition. +
+The messageReceived method will receive the data from the client and write back to \
the client the current time. If the message received from the client is the word \
"quit", then the session will be closed. This method will also print out the current \
time to the client. Depending on the protocol codec that you use, the object (second \
parameter) that gets passed in to this method will be different, as well as the \
object that you pass in to the session.write(Object) method. If you do not specify a \
protocol codec, you will most likely receive a IoBuffer object, and be required to \
write out a IoBuffer object. +
+The sessionIdle method will be called once a session has remained idle for the \
amount of time specified in the call acceptor.getSessionConfig().setIdleTime( \
IdleStatus.BOTH_IDLE, 10 );. +
+All that is left to do is define the socket address that the server will listen on, \
and actually make the call that will start the server. That code is shown below: +
+	:::java
+	import java.io.IOException;
+	import java.net.InetSocketAddress;
+	import java.nio.charset.Charset;
+	
+	import org.apache.mina.core.service.IoAcceptor;
+	import org.apache.mina.core.session.IdleStatus;
+	import org.apache.mina.filter.codec.ProtocolCodecFilter;
+	import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
+	import org.apache.mina.filter.logging.LoggingFilter;
+	import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
+	
+	public class MinaTimeServer
+	{
+		private static final int PORT = 9123;
+		public static void main( String[] args ) throws IOException
+		{
+        	IoAcceptor acceptor = new NioSocketAcceptor();
+			acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
+			acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new \
TextLineCodecFactory( Charset.forName( "UTF-8" )))); +			acceptor.setHandler( new \
TimeServerHandler() ); +			acceptor.getSessionConfig().setReadBufferSize( 2048 );
+			acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
+			acceptor.bind( new InetSocketAddress(PORT) );
+		}
+	}
+
+## Try out the Time server 
+
+At this point, we can go ahead and compile the program.  Once you have compiled the \
program you can run the program in order to test out what happens.  The easiest way \
to test the program is to start the program, and then telnet in to the program: +
+| Client Output | Server Output |
+|---|---|
+| user@myhost:~> telnet 127.0.0.1 9123 <br/>Trying 127.0.0.1... <br/>Connected to \
127.0.0.1. <br/>Escape character is '^]'. <br/>hello <br/>Wed Oct 17 23:23:36 EDT \
2007 <br/>quit <br/>Connection closed by foreign host. <br/>user@myhost:~> | MINA \
Time server started. <br/>Message written... | +
+## What's Next?
+
+Please visit our Documentation page to find out more resources. You can also keep \
reading other tutorials.

Added: mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.3-sample-tcp-client.mdtext
                
URL: http://svn.apache.org/viewvc/mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.3-sample-tcp-client.mdtext?rev=1856368&view=auto
 ==============================================================================
--- mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.3-sample-tcp-client.mdtext \
                (added)
+++ mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.3-sample-tcp-client.mdtext \
Wed Mar 27 05:50:51 2019 @@ -0,0 +1,123 @@
+Title: 2.3 - Sample TCP Client 
+NavUp: ch2-basics.html
+NavUpText: Chapter 2 - Basics
+NavPrev: ch2.2-sample-tcp-server.html
+NavPrevText: 2.2 - Sample TCP Server
+NavNext: ch2.4-sample-udp-server.html
+NavNextText: 2.4 - Sample UDP Server
+Notice:    Licensed to the Apache Software Foundation (ASF) under one
+           or more contributor license agreements.  See the NOTICE file
+           distributed with this work for additional information
+           regarding copyright ownership.  The ASF licenses this file
+           to you under the Apache License, Version 2.0 (the
+           "License"); you may not use this file except in compliance
+           with the License.  You may obtain a copy of the License at
+           .
+             http://www.apache.org/licenses/LICENSE-2.0
+           .
+           Unless required by applicable law or agreed to in writing,
+           software distributed under the License is distributed on an
+           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+           KIND, either express or implied.  See the License for the
+           specific language governing permissions and limitations
+           under the License.
+
+# 2.3 - Sample TCP Client
+
+We have seen the Client Architecture. Lets explore a sample Client implementation.
+
+We shall use [Sumup \
Client](http://mina.apache.org/mina-project/xref/org/apache/mina/example/sumup/Client.html) \
as a reference implementation. +
+We will remove boiler plate code and concentrate on the important constructs. Below \
the code for the Client : +
+	:::java
+	public static void main(String[] args) throws Throwable {
+    	NioSocketConnector connector = new NioSocketConnector();
+		connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
+
+		if (USE_CUSTOM_CODEC) {
+       	connector.getFilterChain().addLast("codec",
+        	new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false)));
+		} else {
+			connector.getFilterChain().addLast("codec",
+            	new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
+    	}
+		
+    	connector.getFilterChain().addLast("logger", new LoggingFilter());
+    	connector.setHandler(new ClientSessionHandler(values));
+		IoSession session;
+		
+		for (;;) {
+        	try {
+            	ConnectFuture future = connector.connect(new \
InetSocketAddress(HOSTNAME, PORT)); +				future.awaitUninterruptibly();
+				session = future.getSession();
+				break;
+			} catch (RuntimeIoException e) {
+				System.err.println(&quot;Failed to connect.&quot;);
+				e.printStackTrace();
+				Thread.sleep(5000);
+			}
+		}
+			
+		// wait until the summation is done
+		session.getCloseFuture().awaitUninterruptibly();
+		connector.dispose();
+	}
+
+To construct a Client, we need to do following
+
+* Create a Connector
+* Create a Filter Chain
+* Create a IOHandler and add to Connector
+* Bind to Server
+
+Lets examine each one in detail
+
+## Create a Connector
+
+	:::java
+	NioSocketConnector connector = new NioSocketConnector();
+
+Here we have created a NIO Socket connector
+
+## Create a Filter Chain
+
+	:::java
+	if (USE_CUSTOM_CODEC) {
+		connector.getFilterChain().addLast("codec",
+        	new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false)));
+	} else {
+		connector.getFilterChain().addLast("codec",
+        	new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
+	}
+
+We add Filters to the Filter Chain for the Connector. Here we have added a \
ProtocolCodec, to the filter Chain. +
+## Create IOHandler
+
+	:::java
+	connector.setHandler(new ClientSessionHandler(values));
+
+Here we create an instance of \
[ClientSessionHandler](http://mina.apache.org/mina-project/xref/org/apache/mina/example/sumup/ClientSessionHandler.html) \
and set it as a handler for the Connector. +
+## Bind to Server
+
+	:::java
+	IoSession session;
+	
+	for (;;) {
+    	try {
+        	ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, \
PORT)); +			future.awaitUninterruptibly();
+			session = future.getSession();
+			break;
+		} catch (RuntimeIoException e) {
+        	System.err.println("Failed to connect.");
+			e.printStackTrace();
+			Thread.sleep(5000);
+		}
+	}
+
+Here is the most important stuff. We connect to remote Server. Since, connect is an \
async task, we use the \
[ConnectFuture](http://mina.apache.org/mina-project/xref/org/apache/mina/core/future/ConnectFuture.html) \
class to know the when the connection is complete. +Once the connection is complete, \
we get the associated \
[IoSession](http://mina.apache.org/mina-project/xref/org/apache/mina/core/session/IoSession.html). \
To send any message to the Server, we shall have to write to the session. All \
responses/messages from server shall traverse the Filter chain and finally be handled \
in IoHandler.

Added: mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.4-sample-udp-server.mdtext
                
URL: http://svn.apache.org/viewvc/mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.4-sample-udp-server.mdtext?rev=1856368&view=auto
 ==============================================================================
--- mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.4-sample-udp-server.mdtext \
                (added)
+++ mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.4-sample-udp-server.mdtext \
Wed Mar 27 05:50:51 2019 @@ -0,0 +1,99 @@
+Title: 2.4 - Sample UDP Server
+NavUp: ch2-basics.html
+NavUpText: Chapter 2 - Basics
+NavPrev: sch2.3-ample-tcp-client.html
+NavPrevText: 2.3 - Sample TCP-CLient
+NavNext: ch2.5-sample-udp-client.html
+NavNextText: 2.5 - Sample UDP Client
+Notice:    Licensed to the Apache Software Foundation (ASF) under one
+           or more contributor license agreements.  See the NOTICE file
+           distributed with this work for additional information
+           regarding copyright ownership.  The ASF licenses this file
+           to you under the Apache License, Version 2.0 (the
+           "License"); you may not use this file except in compliance
+           with the License.  You may obtain a copy of the License at
+           .
+             http://www.apache.org/licenses/LICENSE-2.0
+           .
+           Unless required by applicable law or agreed to in writing,
+           software distributed under the License is distributed on an
+           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+           KIND, either express or implied.  See the License for the
+           specific language governing permissions and limitations
+           under the License.
+
+# 2.4 - Sample UDP Server
+
+We will begin by looking at the code found in the \
[org.apache.mina.example.udp](http://mina.apache.org/mina-project/xref/org/apache/mina/example/udp/package-summary.html) \
package. To keep life simple, we shall concentrate on MINA related constructs only. +
+To construct the server, we shall have to do the following:
+
+1. Create a Datagram Socket to listen for incoming Client requests (See \
[MemoryMonitor.java](http://mina.apache.org/mina-project/xref/org/apache/mina/example/udp/MemoryMonitor.html))
 +2. Create an IoHandler to handle the MINA framework generated events (See \
[MemoryMonitorHandler.java](http://mina.apache.org/mina-project/xref/org/apache/mina/example/udp/MemoryMonitorHandler.html))
 +
+Here is the first snippet that addresses Point# 1:
+
+	:::java
+	NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
+	acceptor.setHandler(new MemoryMonitorHandler(this));
+
+Here, we create a NioDatagramAcceptor to listen for incoming Client requests, and \
set the IoHandler.The variable 'PORT' is just an int. The next step is to add a \
logging filter to the filter chain that this DatagramAcceptor will use. LoggingFilter \
is a very nice way to see MINA in Action. It generate log statements at various \
stages, providing an insight into how MINA works. +
+	:::java
+	DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
+	chain.addLast("logger", new LoggingFilter());
+
+Next we get into some more specific code for the UDP traffic. We will set the \
acceptor to reuse the address +
+	:::java
+	DatagramSessionConfig dcfg = acceptor.getSessionConfig();
+	dcfg.setReuseAddress(true);acceptor.bind(new InetSocketAddress(PORT));
+
+Of course the last thing that is required here is to call bind().
+
+## IoHandler implementation
+
+There are three major events of interest for our Server Implementation
+
+* Session Created
+* Message Received
+* Session Closed
+
+Lets look at each of them in detail
+
+### Session Created Event
+
+	:::java
+	@Override
+	public void sessionCreated(IoSession session) throws Exception {
+    	SocketAddress remoteAddress = session.getRemoteAddress();
+		server.addClient(remoteAddress);
+	} 
+
+In the session creation event, we just call addClient() function, which internally \
adds a Tab to the UI +
+### Message Received Event
+
+	:::java
+	@Override
+	public void messageReceived(IoSession session, Object message) throws Exception {
+        if (message instanceof IoBuffer) {
+            IoBuffer buffer = (IoBuffer) message;
+            SocketAddress remoteAddress = session.getRemoteAddress();
+            server.recvUpdate(remoteAddress, buffer.getLong());
+        }
+	 }
+
+In the message received event, we just dump the data received in the message. \
Applications that need to send responses, can process message and write the responses \
onto session in this function. +
+### Session Closed Event
+
+	:::java
+	@Override
+	public void sessionClosed(IoSession session) throws Exception {
+    	System.out.println("Session closed...");
+		SocketAddress remoteAddress = session.getRemoteAddress();
+		server.removeClient(remoteAddress);
+	}
+
+In the Session Closed, event we just remove the Client tab from the UI

Added: mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.5-sample-udp-client.mdtext
                
URL: http://svn.apache.org/viewvc/mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.5-sample-udp-client.mdtext?rev=1856368&view=auto
 ==============================================================================
--- mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.5-sample-udp-client.mdtext \
                (added)
+++ mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.5-sample-udp-client.mdtext \
Wed Mar 27 05:50:51 2019 @@ -0,0 +1,83 @@
+Title: 2.5 - Sample UDP Client
+NavUp: ch2-basics.html
+NavUpText: Chapter 2 - Basics
+NavPrev: ch2.4-sample-udp-server.html
+NavPrevText: 2.4 - Sample UDP Server
+NavNext: ch2.6-summary.html
+NavNextText: 2.6 - Summary
+Notice:    Licensed to the Apache Software Foundation (ASF) under one
+           or more contributor license agreements.  See the NOTICE file
+           distributed with this work for additional information
+           regarding copyright ownership.  The ASF licenses this file
+           to you under the Apache License, Version 2.0 (the
+           "License"); you may not use this file except in compliance
+           with the License.  You may obtain a copy of the License at
+           .
+             http://www.apache.org/licenses/LICENSE-2.0
+           .
+           Unless required by applicable law or agreed to in writing,
+           software distributed under the License is distributed on an
+           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+           KIND, either express or implied.  See the License for the
+           specific language governing permissions and limitations
+           under the License.
+
+# 2.5 -Sample UDP Client
+
+Lets look at the client code for the UDP Server from previous section.
+
+To implement the Client we need to do following:
+
+* Create Socket and Connect to Server
+* Set the IoHandler
+* Collect free memory
+* Send the Data to the Server
+
+We will begin by looking at the file \
[MemMonClient.java](http://mina.apache.org/mina-project/xref/org/apache/mina/example/udp/client/MemMonClient.html), \
found in the org.apache.mina.example.udp.client java package. The first few lines of \
the code are simple and straightforward. +
+	:::java
+    connector = new NioDatagramConnector();
+    connector.setHandler( this );
+    ConnectFuture connFuture = connector.connect( new InetSocketAddress("localhost", \
MemoryMonitor.PORT )); +
+Here we create a NioDatagramConnector, set the handler and connect to the server. \
One gotcha I ran into was that you must set the host in the InetSocketAddress object \
or else nothing seems to work. This example was mostly written and tested on a \
Windows XP machine, so things may be different elsewhere. Next we will wait for \
acknowledgment that the client has connected to the server. Once we know we are \
connected, we can start writing data to the server. Here is that code: +
+	:::java
+    connFuture.addListener( new IoFutureListener(){
+                public void operationComplete(IoFuture future) {
+                    ConnectFuture connFuture = (ConnectFuture)future;
+                    if( connFuture.isConnected() ){
+                        session = future.getSession();
+                        try {
+                            sendData();
+                        } catch (InterruptedException e) {
+                            e.printStackTrace();
+                        }
+                    } else {
+                        log.error("Not connected...exiting");
+                    }
+                }
+            });
+
+Here we add a listener to the ConnectFuture object and when we receive a callback \
that the client has connected, we will start to write data. The writing of data to \
the server will be handled by a method called sendData. This method is shown below: +
+	:::java
+	private void sendData() throws InterruptedException {
+        for (int i = 0; i < 30; i++) {
+            long free = Runtime.getRuntime().freeMemory();
+            IoBuffer buffer = IoBuffer.allocate(8);
+            buffer.putLong(free);
+            buffer.flip();
+            session.write(buffer);
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+                throw new InterruptedException(e.getMessage());
+            }
+        }
+	}
+
+This method will write the amount of free memory to the server once a second for 30 \
seconds. Here you can see that we allocate a IoBuffer large enough to hold a long \
variable and then place the amount of free memory in the buffer. This buffer is then \
flipped and written to the server. +
+Our UDP Client implementation is complete.

Added: mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.6-summary.mdtext
URL: http://svn.apache.org/viewvc/mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.6-summary.mdtext?rev=1856368&view=auto
 ==============================================================================
--- mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.6-summary.mdtext \
                (added)
+++ mina/site/trunk/content/mina-project/userguide/ch2-basics/ch2.6-summary.mdtext \
Wed Mar 27 05:50:51 2019 @@ -0,0 +1,27 @@
+Title: 2.6 - Summary
+NavUp: ch2-basics.html
+NavUpText: Chapter 2 - Basics
+NavPrev: ch2.5-sample-udp-client.html
+NavPrevText: 2.5 - Sample UDP client
+Notice:    Licensed to the Apache Software Foundation (ASF) under one
+           or more contributor license agreements.  See the NOTICE file
+           distributed with this work for additional information
+           regarding copyright ownership.  The ASF licenses this file
+           to you under the Apache License, Version 2.0 (the
+           "License"); you may not use this file except in compliance
+           with the License.  You may obtain a copy of the License at
+           .
+             http://www.apache.org/licenses/LICENSE-2.0
+           .
+           Unless required by applicable law or agreed to in writing,
+           software distributed under the License is distributed on an
+           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+           KIND, either express or implied.  See the License for the
+           specific language governing permissions and limitations
+           under the License.
+
+# 2.6 - Summary
+
+In this chapter, we looked at MINA based Application Architecture, for Client as \
well as Server. We also touched upon the implementation of Sample TCP Server/Client, \
and UDP Server and Client. +
+In the chapters to come we shall discuss about MINA Core constructs and advanced \
topics


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic