Apache的MINA是一个被用来构建高性能和高可伸缩性应用程序的网络应用框架,它提供了一套统一的建立在Java NIO之上的事件驱动的异步API。
对于MINA框架的了解,MINA官方的几篇文章是必须要看的,如下:
* Application Architecture http://mina.apache.org/mina-based-application-architecture.html
* Server Architecture http://mina.apache.org/server-architecture.html
* Client Architecture http://mina.apache.org/client-architecture.html
其中几个主要的组件如下:
I/O Service - 用来处理I/O流,对于Server端就是IOAcceptor的实现类接受Client端的连接请求,对于Client端就是IoConnector的实现类来建立到Server端的连接。
I/O Filter Chain - 用来过滤或转化数据。对于Server端和Client端来说都是IoFilter接口的实现类,MINA自己内建了很多IoFilter接口的实现类。具体可以参考官方文档。
I/O Handler - 用来处理真正业务逻辑的类。对于Server端和Client端来说都是IoHandler接口的实现类,通常来说需要自己编写。
由于Server端和Client端都是基于以上三个组件的,因此对于Server端和Client端编程来说就都有类似的代码结构。
对于Server端来说:
1. 创建I/O service - 这里就是创建IOAcceptor类监听端口。
2. 创建I/O Filter Chain - 这里就是告诉使用那些IoFilter。
3. 创建I/O Handler - 自己的业务逻辑。
对于Client端来说:
1. 创建I/O service - 这里就是创建IOConnector类来建立到Server端的连接。
2. 创建I/O Filter Chain - 这里就是告诉使用那些IoFilter。
3. 创建I/O Handler - 自己的业务逻辑。
下面来通过一个例子看看MINA是怎样工作的。由于大多数应用都是基于TCP/IP的应用,所以这里也就不再说UDP/IP了。
这里我使用了Maven来创建了一个简单java应用程序,具体步骤请参Maven的官方手册。这里只是将我用到的maven配置文件pom.xml列出,方便下面及后续文章使用。具体pom.xml文件内容如下:
- <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.google.code.garbagecan.minastudy</groupId>
- <artifactId>minastudy</artifactId>
- <packaging>jar</packaging>
- <version>1.0-SNAPSHOT</version>
- <name>minastudy</name>
- <url>http://maven.apache.org</url>
- <dependencies>
- <dependency>
- <groupId>org.apache.mina</groupId>
- <artifactId>mina-core</artifactId>
- <version>2.0.4</version>
- </dependency>
- <dependency>
- <groupId>org.apache.mina</groupId>
- <artifactId>mina-filter-compression</artifactId>
- <version>2.0.4</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.3.0</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.3.0</version>
- </dependency>
- </dependencies>
- </project>
- packagecom.google.code.garbagecan.minastudy.sample1;
- importjava.io.IOException;
- importjava.net.InetSocketAddress;
- importjava.nio.charset.Charset;
- importorg.apache.mina.core.service.IoAcceptor;
- importorg.apache.mina.core.service.IoHandlerAdapter;
- importorg.apache.mina.core.session.IdleStatus;
- importorg.apache.mina.core.session.IoSession;
- importorg.apache.mina.filter.codec.ProtocolCodecFilter;
- importorg.apache.mina.filter.codec.textline.TextLineCodecFactory;
- importorg.apache.mina.filter.logging.LoggingFilter;
- importorg.apache.mina.transport.socket.nio.NioSocketAcceptor;
- importorg.slf4j.Logger;
- importorg.slf4j.LoggerFactory;
- publicclassMyServer{
- privatestaticfinalLoggerlogger=LoggerFactory.getLogger(MyServer.class);
- publicstaticvoidmain(String[]args){
- IoAcceptoracceptor=newNioSocketAcceptor();
- acceptor.getFilterChain().addLast("logger",newLoggingFilter());
- acceptor.getFilterChain().addLast("codec",newProtocolCodecFilter(newTextLineCodecFactory(Charset.forName("UTF-8"))));
- acceptor.setHandler(newIoHandlerAdapter(){
- @Override
- publicvoidsessionCreated(IoSessionsession)throwsException{
- }
- @Override
- publicvoidsessionOpened(IoSessionsession)throwsException{
- }
- @Override
- publicvoidsessionClosed(IoSessionsession)throwsException{
- }
- @Override
- publicvoidsessionIdle(IoSessionsession,IdleStatusstatus)throwsException{
- }
- @Override
- publicvoidexceptionCaught(IoSessionsession,Throwablecause)throwsException{
- logger.error(cause.getMessage(),cause);
- session.close(true);
- }
- @Override
- publicvoidmessageReceived(IoSessionsession,Objectmessage)throwsException{
- logger.info("Receivedmessage"+message);
- session.write(message);
- }
- @Override
- publicvoidmessageSent(IoSessionsession,Objectmessage)throwsException{
- logger.info("Sentmessage"+message);
- }
- });
- try{
- acceptor.bind(newInetSocketAddress(10000));
- }catch(IOExceptionex){
- logger.error(ex.getMessage(),ex);
- }
- }
- }
2. 创建I/O Filter Chain,这里使用了两个IoFilter,一个是LoggingFilter用来记录日志和打印事件消息,另一个是ProtocolCodecFilter实例用来编码数据,这里其实就是将传递的数据编码成文本。
3. 创建I/O Handler,不要害怕,看起来代码多,其实就是一个实现了IoHandler接口的子类,自己需要实现其中的一些方法,这里方法比较多,但是我在这里只实现了messageSent,messageReceived和exceptionCaught方法。
4. 最后就是让IoAcceptor类实例绑定端口实现监听。
下面看看Client端的代码
- packagecom.google.code.garbagecan.minastudy.sample1;
- importjava.net.InetSocketAddress;
- importjava.nio.charset.Charset;
- importorg.apache.mina.core.RuntimeIoException;
- importorg.apache.mina.core.future.ConnectFuture;
- importorg.apache.mina.core.service.IoConnector;
- importorg.apache.mina.core.service.IoHandlerAdapter;
- importorg.apache.mina.core.session.IdleStatus;
- importorg.apache.mina.core.session.IoSession;
- importorg.apache.mina.filter.codec.ProtocolCodecFilter;
- importorg.apache.mina.filter.codec.textline.TextLineCodecFactory;
- importorg.apache.mina.filter.logging.LoggingFilter;
- importorg.apache.mina.transport.socket.nio.NioSocketConnector;
- importorg.slf4j.Logger;
- importorg.slf4j.LoggerFactory;
- publicclassMyClient{
- privatestaticfinalLoggerlogger=LoggerFactory.getLogger(MyClient.class);
- publicstaticvoidmain(String[]args){
- IoConnectorconnector=newNioSocketConnector();
- connector.setConnectTimeoutMillis(10*1000);
- connector.getFilterChain().addLast("logger",newLoggingFilter());
- connector.getFilterChain().addLast("codec",newProtocolCodecFilter(newTextLineCodecFactory(Charset.forName("UTF-8"))));
- connector.setHandler(newIoHandlerAdapter(){
- @Override
- publicvoidsessionCreated(IoSessionsession)throwsException{
- }
- @Override
- publicvoidsessionOpened(IoSessionsession)throwsException{
- for(inti=0;i<10;i++){
- session.write("Hellouser_"+i);
- }
- session.write("Bye");
- }
- @Override
- publicvoidsessionClosed(IoSessionsession)throwsException{
- }
- @Override
- publicvoidsessionIdle(IoSessionsession,IdleStatusstatus)throwsException{
- }
- @Override
- publicvoidexceptionCaught(IoSessionsession,Throwablecause)throwsException{
- logger.error(cause.getMessage(),cause);
- session.close(true);
- }
- @Override
- publicvoidmessageReceived(IoSessionsession,Objectmessage)throwsException{
- logger.info("Receivedmessage"+message);
- if(message.toString().equalsIgnoreCase("Bye")){
- session.close(true);
- }
- }
- @Override
- publicvoidmessageSent(IoSessionsession,Objectmessage)throwsException{
- logger.info("Sentmessage"+message);
- }
- });
- IoSessionsession=null;
- try{
- ConnectFuturefuture=connector.connect(newInetSocketAddress("localhost",10000));
- future.awaitUninterruptibly();
- session=future.getSession();
- }catch(RuntimeIoExceptione){
- logger.error(e.getMessage(),e);
- }
- session.getCloseFuture().awaitUninterruptibly();
- connector.dispose();
- }
- }
1. 首先创建I/O Service,这里使用的是NioSocketConnector类来创建了一个IoConnector实例,并设置连接超时为10秒。
2. 创建I/O Filter Chain,和服务器端同样设置了两个IoFilter,一个是LoggingFilter用来记录日志和打印事件消息,另一个是ProtocolCodecFilter实例用来编码数据,这里其实就是将传递的数据编码成文本。
3. 创建I/O Handler,也不要害怕,看起来代码多,其实也是一个实现了IoHandler接口的子类,并且自己实现了sessionOpened,messageSent,messageReceived和exceptionCaught方法。实现sessionOpened方法是为了在建立连接后向Server端发送消息。另外看一下messageReceived方法实现,在接收到服务器端的消息后关闭会话。从而可以使Client程序最终能够退出。
4. 最后就是IoConnector实例类连接远端的Server。
下面测试一下上面的程序,首先运行MyServer类,然后运行MyClient类,就可以分别在各自的终端上看到事件日志以及发送/接收的消息了。
利用Apache MINA来传递对象,这对了MINA来说非常容易,并且这也是Java网络编程中很常用的应用。其实对于MINA传递对象来说,如果看过前一篇文章的话,只要在其中做少许改动就可以实现对象传递,但这里考虑到例子的完整性,还是给出了全部代码示例。
首先看两个用来传递的Java对象MyRequestObject和MyResponseObject,很简单只是实现了Serializable接口罢了。
1.package com.google.code.garbagecan.minastudy.sample3;
2.
3.import java.io.Serializable; 4.
5.public class MyRequestObject implements Serializable { 6.
7. private static final long serialVersionUID = 1L; 8.
9. private String name; 10.
11. private String value; 12.
13. public MyRequestObject(String name, String value) { 14. this.name = name; 15. this.value = value; 16. }
17.
18. public String getName() { 19. return name; 20. }
21.
22. public void setName(String name) { 23. this.name = name; 24. }
25.
26. public String getValue() { 27. return value; 28. }
29.
30. public void setValue(String value) { 31. this.value = value; 32. }
33.
34. @Override 35. public String toString() { 36. StringBuffer sb = new StringBuffer(); 37. sb.append("Request [name: " + name + ", value: " + value + "]"); 38. return sb.toString(); 39. }
40.}
41.
42.package com.google.code.garbagecan.minastudy.sample3; 43.
44.import java.io.Serializable; 45.
46.public class MyResponseObject implements Serializable { 47.
48. private static final long serialVersionUID = 1L; 49.
50. private String name; 51.
52. private String value; 53.
54. public MyResponseObject(String name, String value) { 55. this.name = name; 56. this.value = value; 57. }
58.
59. public String getName() { 60. return name; 61. }
62.
63. public void setName(String name) { 64. this.name = name; 65. }
66.
67. public String getValue() { 68. return value; 69. }
70.
71. public void setValue(String value) { 72. this.value = value; 73. }
74.
75. @Override 76. public String toString() { 77. StringBuffer sb = new StringBuffer(); 78. sb.append("Response [name: " + name + ", value: " + value + "]"); 79. return sb.toString(); 80. }
81.}
看看Server端的代码
1.package com.google.code.garbagecan.minastudy.sample3;
2.
3.import java.io.IOException; 4.import java.net.InetSocketAddress; 5.
6.import org.apache.mina.core.service.IoAcceptor; 7.import org.apache.mina.core.service.IoHandlerAdapter; 8.import org.apache.mina.core.session.IdleStatus; 9.import org.apache.mina.core.session.IoSession; 10.import org.apache.mina.filter.codec.ProtocolCodecFilter; 11.import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; 12.import org.apache.mina.filter.logging.LoggingFilter; 13.import org.apache.mina.transport.socket.nio.NioSocketAcceptor; 14.import org.slf4j.Logger; 15.import org.slf4j.LoggerFactory; 16.
17.public class MyServer { 18.
19. private static final Logger logger = LoggerFactory.getLogger(MyServer.class); 20.
21. public static void main(String[] args) { 22. IoAcceptor acceptor = new NioSocketAcceptor(); 23.
24. acceptor.getFilterChain().addLast("logger", new LoggingFilter()); 25. acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); 26.
27. acceptor.setHandler(new IoHandlerAdapter() { 28.
29. @Override 30. public void sessionCreated(IoSession session) throws Exception { 31. }
32.
33. @Override 34. public void sessionOpened(IoSession session) throws Exception { 35. }
36.
37. @Override 38. public void sessionClosed(IoSession session) throws Exception { 39. }
40.
41. @Override 42. public void sessionIdle(IoSession session, IdleStatus status) throws Exception { 43. }
44.
45. @Override 46. public void exceptionCaught(IoSession session, Throwable cause) throws Exception { 47. logger.error(cause.getMessage(), cause);
48. session.close(true); 49. }
50.
51. @Override 52. public void messageReceived(IoSession session, Object message) throws Exception { 53. logger.info("Received " + message); 54. MyRequestObject myReqOjb = (MyRequestObject) message;
55. MyResponseObject myResObj = new MyResponseObject(myReqOjb.getName(), myReqOjb.getValue()); 56. session.write(myResObj);
57. }
58.
59. @Override 60. public void messageSent(IoSession session, Object message) throws Exception { 61. logger.info("Sent " + message); 62. }
63. });
64.
65. try { 66. acceptor.bind(new InetSocketAddress(10000)); 67. } catch (IOException ex) { 68. logger.error(ex.getMessage(), ex);
69. }
70. }
71.}
1. 首先创建I/O Service,这里使用的是NioSocketAcceptor类来创建了一个IoAcceptor实例。
2. 创建I/O Filter Chain,这里使用了两个个IoFilter,一个是LoggingFilter用来记录日志和打印事件消息,另一个是ProtocolCodecFilter实例用来编码数据,这里使用了ObjectSerializationCodecFactory类来序列化或反序列化数据成java对象。
3. 创建I/O Handler,这里主要看一下messageReceived方法,其总接收了MyRequestObject对象,然后又发送了一个MyResponseObject对象给Client端。
4. 最后就是让IoAcceptor类实例绑定端口实现监听。
看看Client端的代码
1.package com.google.code.garbagecan.minastudy.sample3;
2.
3.import java.net.InetSocketAddress; 4.
5.import org.apache.mina.core.RuntimeIoException; 6.import org.apache.mina.core.future.ConnectFuture; 7.import org.apache.mina.core.service.IoConnector; 8.import org.apache.mina.core.service.IoHandlerAdapter; 9.import org.apache.mina.core.session.IdleStatus; 10.import org.apache.mina.core.session.IoSession; 11.import org.apache.mina.filter.codec.ProtocolCodecFilter; 12.import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; 13.import org.apache.mina.filter.logging.LoggingFilter; 14.import org.apache.mina.transport.socket.nio.NioSocketConnector; 15.import org.slf4j.Logger; 16.import org.slf4j.LoggerFactory; 17.
18.public class MyClient { 19.
20. private static final Logger logger = LoggerFactory.getLogger(MyClient.class); 21.
22. public static void main(String[] args) { 23. IoConnector connector = new NioSocketConnector(); 24. connector.setConnectTimeoutMillis(10 * 1000); 25.
26. connector.getFilterChain().addLast("logger", new LoggingFilter()); 27. connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); 28.
29. connector.setHandler(new IoHandlerAdapter() { 30.
31. @Override 32. public void sessionCreated(IoSession session) throws Exception { 33. }
34.
35. @Override 36. public void sessionOpened(IoSession session) throws Exception { 37. MyRequestObject myObj = new MyRequestObject("my name", "my value"); 38. session.write(myObj);
39. }
40.
41. @Override 42. public void sessionClosed(IoSession session) throws Exception { 43. }
44.
45. @Override 46. public void sessionIdle(IoSession session, IdleStatus status) throws Exception { 47. }
48.
49. @Override 50. public void exceptionCaught(IoSession session, Throwable cause) throws Exception { 51. logger.error(cause.getMessage(), cause);
52. session.close(true); 53. }
54.
55. @Override 56. public void messageReceived(IoSession session, Object message) throws Exception { 57. MyResponseObject myResObj = (MyResponseObject) message;
58. logger.info("Received " + myResObj); 59. session.close(true); 60. }
61.
62. @Override 63. public void messageSent(IoSession session, Object message) throws Exception { 64. logger.info("Sent " + message); 65. }
66. });
67.
68. IoSession session = null; 69. try { 70. ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 10000)); 71. future.awaitUninterruptibly();
72. session = future.getSession();
73. } catch (RuntimeIoException e) { 74. logger.error(e.getMessage(), e);
75. }
76.
77. session.getCloseFuture().awaitUninterruptibly();
78. connector.dispose();
79. }
80.}
1. 首先创建I/O Service,这里使用的是NioSocketConnector类来创建了一个IoConnector实例,并设置连接超时为10秒。
2. 创建I/O Filter Chain,和服务器端同样设置了两个IoFilter,一个是LoggingFilter用来记录日志和打印事件消息,另一个是ProtocolCodecFilter实例用来编码数据,这里也使用了ObjectSerializationCodecFactory类来序列化或反序列化数据成java对象。
3. 创建I/O Handler,主要看一下sessionOpened方法,其中在会话建立事件中发送了MyRequestObject对象,然后在messageReceived方法中又接受了MyResponseObject对象。
4. 最后就是IoConnector实例类连接远端的Server。
下面测试一下上面的程序,首先运行MyServer类,然后运行MyClient类,就可以分别在各自的终端上看到事件日志以及发送/接收的对象了。