设为首页 收藏本站
查看: 609|回复: 0

[经验分享] apache mina 入门指导翻译

[复制链接]

尚未签到

发表于 2017-1-1 07:42:41 | 显示全部楼层 |阅读模式
Quick Start Guide
  快速开始指导
This tutorial will walk you through the process of building a MINA based program. This tutorial will walk
这个指导奖贯穿建立MINA程序的基本过程,这个指导奖建立一个时间服务程序,这个指导需要下面的。
through building a time server. The following prerequisites are required for this tutorial:
 


  • MINA 2.0.7 Core
  • JDK 1.5 or greater
  • [SLF4J|http://www.slf4j.org/] 1.3.0 or greater


    • Log4J 1.2 users: slf4j-api.jarslf4j-log4j12.jar, and Log4J 1.2.x

    • Log4J 1.3 users: slf4j-api.jarslf4j-log4j13.jar, and Log4J 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.



I have tested this program on both Windows© 2000 professional and linux. If you have any problems
我已经在Windows2000专业版和linux上测试了这个程序,如果你在运行这个程序是遇到任何的问题,
getting this program to work, please do not hesitate to [contact us|Contact] in order to talk to the MINA
为了MINA的开发者请立即联系我们,还有;这个指导已经有独立的IDE,或者编辑器, 还有; 这个指导将能和你任何其他的环境稳定的工作,
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
编译和执行程序步骤再次省了,如果你需要学习如何编译和运行java程序,请看...
commands and steps to execute the program have been removed for brevity. If you need help learning how to either compile of execute java programs, please consult the Java tutorial.

Writing the MINA time server
  写MINA时间服务
We will begin by creating a file called MinaTimeServer.java. The initial code can be found below: :::Java
我们将开始创建一个叫 MinaTimeServer.java的文件,文件的code如下。
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
这个code应该是直接的,我们见到的定义了main方法这个main方法将启动这个程序。
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
我们需要一个对象去listen所有的连接,因为我们是基于TCP/IP的,我们将添加一个SocketAcceptor。
TCP/IP based, we will add a SocketAcceptor to our program.

import org.apache.mina.core.service.IoAcceptor;
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类的地方,我们可以定义这个类的handler和绑定NioSocketAcceptor到一个端口
NioSocketAcceptor to a port.
Next we add a filter to the configuration. This filter will log all information such as newly created
下一步我们添加一个filter到配置中,这个filter将记录所有的信息比如最近创建的会话
sessions, messages received, messages sent, session closed. The next filter is a ProtocolCodecFilter.
收到的消息,发生的消息,和会话关闭,下一个filter是ProtocolCodecFilter.
This filter will translate binary or protocol specific data into message object and vice versa. We use an
这个filter将把二进制和特别协议的数据转换成消息对象,
existing TextLine factory because it will handle text base message for you (you don't have to write the
我们使用一个存在的TextLine工厂,因为它能处理文本的消息
codec part)

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" ))));
}
}



At this point, we will define the handler that will be used to service client connections and the requests
我们将定义这个我们服务端和客户端连接的和时间请求的处理器,这个处理器类必须实现IoHandler接口,
for the current time. The handler class is a class that must implement the interface IoHandler. For
对应大多数MINA程序,这个会是程序的重点,当服务接收到客户端的请求,在这里,我们将继承IoHandlerAdapter
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 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.

import java.io.IOException;
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() );
}
}



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.

import java.io.IOException;
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 );
}
}



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:

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 exceptionCaughtmessageReceived and sessionIdleexceptionCaught 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 callacceptor.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:

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
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hello
Mon Apr 09 23:42:55 EDT 2007
quit
Connection closed by foreign host.
user@myhost:~>
MINA Time server started.
Session created...
Message written...




运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-322146-1-1.html 上篇帖子: SVN+Apache安装指南 下篇帖子: apache整合tomcat以及svn
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表