日期:2014-05-16  浏览次数:20809 次

Apache MINA (2) Hello World!

了解完Apach MINA的一些基本概念Apache MINA (1) 简介 ,开始进入MINA相关的代码学习,以一个简单HelloWorld程序开始,完成客户端与服务端之间的通讯。

?

准备工作:
org.apache.mina 版本4.0
org.slf4j 1.6.1 (Simple Logging Facade for Java)mina所使用的日志框架,该版本是与mina4.0匹配的版本。
我是用maven管理项目依赖的,使用apache-maven-3.0.4
IDE:IntelliJ IDEA 10.0.3

?

开始HelloWorld:

1.maven的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<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>example</groupId>
    <artifactId>example</artifactId>
    <version>1.0</version>

    <properties>
        <project.build.sourceEncoding>GBK</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>

    </dependencies>  
    
</project>

?2. 服务器代码:

??? a) 首先实现服务端的IoHandler代码SimpleMinaServerHandler。主要功能是打印客户端写入的信息,统计客户端的请求次数以及返回当前客户端是第几次访问。

package com.chiyan.apach.mina.server;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by IntelliJ IDEA.
 * 简单的消息处理器
 * User: chiyan
 * Date: 12-7-19
 * Time: 上午12:19
 */
public class SimpleMinaServerHandler extends IoHandlerAdapter {

	private AtomicInteger count = new AtomicInteger(0);

	/**
	 * 当一个客户端连接进入时
	 */
	@Override
	public void sessionOpened(IoSession session) throws Exception {

		System.out.println("client connection : " + session.getRemoteAddress());

	}

	/**
	 * 当一个客户端关闭时
	 */
	@Override
	public void sessionClosed(IoSession session) throws Exception {

		System.out.println("client disconnection : " +session.getRemoteAddress() + " is Disconnection");

	}

    /**
     * 当接收到客户端的信息
     *
     * @param session
     * @param message
     * @throws Exception
     */
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {

		String str = (String)message;

        // 打印客户端
		System.out.println("receive client message : [ " + str +" ]");

		// 回写消息给客户端
		session.write(count.incrementAndGet());

	}

}

?b) 搭建服务端 MainServer:

package com.chiyan.apach.mina.server;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
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.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * Created by IntelliJ IDEA.
 * User: chiyan
 * Date: 12-7-19
 * Time: 上午12:27
 */
public class MainServer {

    // 服务器端口
    private static final int SERVER_PORT = 8899;

    public