- 浏览: 580047 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (253)
- java (84)
- python (22)
- 设计模式 (12)
- 数据结构和算法 (7)
- ibatis (1)
- 数据挖掘 (2)
- 集体智慧读书笔记 (1)
- ubuntu (4)
- lucene (11)
- 算法 第4版 (11)
- apache mina (16)
- memcached (1)
- android (9)
- netty (6)
- mongodb (2)
- maven (2)
- openfire (2)
- 服务端 (21)
- 产品 (0)
- apache (1)
- 选择 (2)
- 构架WEB高性能站点 (7)
- redis (8)
- 诗词歌赋 (3)
- 源代码阅读 (5)
- 前端 (1)
- javascript (3)
- guice (1)
- 分布式 (5)
- 总结-2014 (4)
- jvm (1)
最新评论
-
liu_jiaqiang:
写的挺好
maven多项目管理 -
H972900846:
我想知道哪里整的,如果是自己写的,那有点牛呀如果是抄的请说明出 ...
SSL身份认证原理 -
春天好:
博主写的很好,赞一个,多谢分享 *(^-^*)分享一个免费好用 ...
定向网站爬虫---初级例子 -
fenglingabc:
经过测试,parameterType="java.u ...
mybatis获取主键和存储过程返回值 -
jyghqpkl:
[u][/u] ...
Cookie的secure 属性
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.jar, slf4j-log4j12.jar, and Log4J 1.2.x
- Log4J 1.3 users: slf4j-api.jar, slf4j-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 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 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:
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... |
发表评论
-
protobuf-dt插件
2015-03-24 13:16 1421protobuf-dt: 安装前先安装xtext 可 ... -
java循环标签
2015-03-20 16:13 610今天看 源码的时候 看到 一个小语法 参考: ... -
java程序性能优化 --阅读
2014-10-14 17:56 709闲着,真实无聊; 发现一本好书《java程序性能优 ... -
jetty invalid entry CRC问题
2014-08-04 11:42 16121: http://stackoverflow.com/qu ... -
guice注入
2014-05-24 12:13 9449Google Guice3.0: http://code. ... -
eclipse快捷键
2014-05-21 16:01 5781: clrl+alt+r : 最常用,快速定位到文件 2 ... -
java clone
2014-05-16 17:04 527转:http://www.blogjava.net/ora ... -
ThreadLocal
2014-05-13 18:39 772简单介绍一下ThreadLocal的原理:1.Thread ... -
hession
2014-04-30 12:33 697一、首先先说Hessian是什么? Hessian:he ... -
冒泡和快速排序java
2014-04-19 18:01 7591: 冒泡最简单一种: /** * 算法效率o ... -
java生产者和消费者模型三种实现
2014-04-19 17:51 13671: 生产者和消费者的问题,生产者生产产品到缓冲区,消费者 ... -
单例模式
2014-03-14 16:06 750今天看到群里,关于单例模式的多线程下的安全问题: 1:最 ... -
freemarker的使用
2014-02-28 16:42 8421:freemarker eclipse插件安装方法:ht ... -
java 引用类型和内存泄露
2013-11-21 17:48 585http://blog.csdn.net/luoshenfu ... -
java泛型
2013-11-07 13:52 436Class<T>在实例化的时候,T要替换成具体 ... -
filter执行顺序
2013-10-12 11:16 1124多个筛选器的运行顺序取决于下列规则: 将 filt ... -
spring rmi远程调用
2013-09-09 11:48 11771:以前用jmi发布服务,实现分布式的一种方式,远程调用, ... -
spring mvc返回204状态码
2013-07-24 09:27 39271:204是没内容 不跳转的 代表请求成功的意思 ... -
editplus去掉多余空行
2013-07-19 21:05 7391: ^[ \t]*\n 用正则表达式替换 -
spring3 aop 使用详细
2013-06-06 11:10 01:目标:拦截所有的@Controller中的方法 ...
相关推荐
《Apache Mina2官方教程翻译》是Mina2的官方文档中文版,详细介绍了如何使用Mina进行网络编程。这份文档将帮助你理解Mina的核心概念,包括过滤器链、事件驱动模型和I/O多路复用技术。通过学习,你可以了解到如何创建...
Server_2%5B1%5D.0%E4%B8%AD%E6%96%87%E5%8F%82%E8%80%83%E6%89%8B%E5%86%8CV1.0.pdf**:这是一份中文版的Apache Mina Server 2.0.0教程,可能涵盖了如何配置和使用Mina服务器端的基本概念、配置示例以及实战指导。...
MINA (Java IO Network ...总的来说,这个压缩包为初学者提供了一套完整的MINA学习资源,涵盖了理论知识、API详解和实战指导,有助于开发者快速入门并精通MINA框架,从而在实际工作中实现高效、稳定的网络通信应用。
2. 用户指南:指导如何安装、配置和部署MINA服务器,以及如何创建自定义协议处理器。 3. 故障排查:列出常见问题和解决方案,帮助开发者解决遇到的问题。 4. 示例代码:包含丰富的示例代码,演示了如何使用MINA构建...
- **Apache_Mina_Server_2.0中文参考手册V1.0.pdf**:这是MINA 2.0版本的中文参考手册,提供了详细的API介绍和技术指导,是深入学习MINA的重要资料。 - **MINA使用手记[1] .shtml**和**MINA框架使用总结 .shtml**:...
Apache MINA(Multipurpose Infrastructure for Network Applications)是一个高性能、异步事件驱动的网络应用程序框架,主要用Java语言编写。MINA旨在简化开发高效且可扩展的网络服务,如TCP/IP和UDP协议的应用。本...
MINA2,全称为“Java Multithreaded Network Application Framework”,是Apache软件基金会的一个开源项目,主要用于构建高性能、高可扩展性的网络应用。这个压缩包包含的资源是MINA2的用户手册,分别有中文和英文两...
- **Apache MINA**:一个网络框架。 ### 快速入门指南 为了快速开始使用Apache Camel,读者可以从本章节的一些简单示例入手。这些示例将引导用户了解如何设置环境、创建基本的路由和处理消息传递。 ### 结论 ...
Mina,全称为Apache Mina,是一款基于Java的网络通信应用框架,主要用于简化高性能服务器的开发。它为开发者提供了低级、事件驱动的网络应用程序接口,使得构建跨平台、跨协议的服务变得更加简单。在软件设计和软件...
- **开发第一个应用程序**:指导用户通过一个简单的示例来开发他们的第一个 Apache Camel 应用程序。 - **配置和管理**:提供关于如何配置和管理 Apache Camel 应用程序的信息。 - **高级主题**:探讨更复杂的主题,...
- Apache MINA:一个高性能的NIO驱动的网络框架。 Camel的核心概念在于它的集成模式,它们是一种设计模式,可以用来指导集成系统的开发。Camel支持许多这样的模式,并提供了一种声明式的路由和转换规则语言,允许...
简介 笔者当初为了学习JAVA,收集了很多经典源码,源码难易程度分为初级、中级、高级等,详情看源码列表,需要的可以直接下载! 这些源码反映了那时那景笔者对未来的盲目,对代码的热情、执着,对IT的憧憬、向往!...