Mina入门:mina版之HelloWorld
[z]
一,前言:
在完成上篇文章《Mina入门:Java NIO框架Mina、Netty、Grizzly简介与对比》之后,我们现在可以正式切入Mina入门学习了。
http://i.cnblogs.com/EditPosts.aspx?opt=1
二,搭建项目结构与解决项目依赖
本人使用Maven来管理项目的依赖。好了,废话也不多说,直接上pom.xml。这里主要是加入mina-core以及其依赖的SLF4J。
<project xmlns="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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.androidwhy</groupId>
- <artifactId>mina-helloworld</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>mina-helloworld</name>
- <url>http://www.androidwhy.com</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.apache.mina</groupId>
- <artifactId>mina-core</artifactId>
- <version>2.0.4</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>jcl-over-slf4j</artifactId>
- <version>1.6.1</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-nop</artifactId>
- <version>1.6.1</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- </project>
这里需要注意一点的就是Mina与SLF4J版本的匹配,官方也有文档提到了,注意一下就是。
三,编写服务器
我们的mina版的HelloWorld的业务逻辑很简单,就是接收客户端的请求,并回应给客户端一个字符"Hello,I am Server!"就可以了。
MinaTimeServer的主代码如下。
package com.androidwhy.mina.helloworld.server;
- 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 {
- <span style="white-space: pre;"> </span>private static final int PORT = 8888;
- public static void main(String[] args) throws IOException {
- // Create the acceptor
- IoAcceptor acceptor = new NioSocketAcceptor();
- // Add two filters : a logger and a codec
- acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
- acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
- // Attach the business logic to the server
- acceptor.setHandler( new HelloWorldServerHandler() );
- // Configurate the buffer size and the iddle time
- acceptor.getSessionConfig().setReadBufferSize( 2048 );
- acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
- // And bind !
- acceptor.bind( new InetSocketAddress(PORT) );
- }
- }
Handler代码如下:
package com.androidwhy.mina.helloworld.server;
- import org.apache.mina.core.service.IoHandlerAdapter;
- import org.apache.mina.core.session.IdleStatus;
- import org.apache.mina.core.session.IoSession;
- public class HelloWorldServerHandler extends IoHandlerAdapter
- {
- /**
- * Trap exceptions.
- */
- @Override
- public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
- {
- cause.printStackTrace();
- }
- /**
- * If the message is 'quit', we exit by closing the session. Otherwise,
- * we return the message.
- */
- @Override
- public void messageReceived( IoSession session, Object message ) throws Exception
- {
- String str = message.toString();
- if( str.trim().equalsIgnoreCase("quit") ) {
- // "Quit" ? let's get out ...
- session.close(true);
- return;
- }
- System.out.println("Received message:"+str);
- // Send the "Hello, I am Server!" back to the client
- String helloWorld = "Hello, I am Server!";
- session.write(helloWorld);
- System.out.println("Message written...");
- }
- /**
- * On idle, we just write a message on the console
- */
- @Override
- public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
- {
- System.out.println( "IDLE " + session.getIdleCount( status ));
- }
- }
你会发现,使用Mina写一个Server就是如此之简单!上面的MinaTimeServer主是建立一个监听在8888端口(建议使用大于1024的端口号,因为1024以下的是系统保留的)服务,并设置了一个日志filter与一个编码的filter;HelloWorldServerHandler对handler的各位状态进行了处理,在这里最为主要的就是override了messageReceived方法,并在其中处理我们的业务逻辑。
四,运行程序
到目前为止,我们只是写了一个Server,那程序怎么跑呢?客户端就暂时采用Telnet吧!
五,总结
我只想说一句:任何开源框架的入门都是如此的Easy,Mina也一样。