市面上比较成熟的nio框架很少,其中做的比较好的就是apache的nio和jboss的netty了。因为apache是主流,所以可能mina用的较多。
到apache官网下载最新版的mina。接着mina官方给出的例子一起学习下mina。
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.example.gettingstarted.timeserver;
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.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
/**
* A minimal 'time' server, returning the current date. Opening a telnet server,
* you will get the current date by typing any string followed by a new line.
*
* In order to quit, just send the 'quit' message.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MinaTimeServer {
/**
* We will use a port above 1024 to be able to launch the server with a
* standard user
*/
private static final int PORT = 9123;
/**
* The server implementation. It's based on TCP, and uses a logging filter
* plus a text line decoder.
*/
public static void main(String[] args) throws IOException {
// Create the acceptor
IoAcceptor acceptor = new NioSocketAcceptor();//ServerSocketChannel的实现,作为服务器
// 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"), LineDelimiter.WINDOWS.getValue(),
LineDelimiter.WINDOWS.getValue())));//linedelimiter是输入流的简单封装
//getfilerechain函数是过滤器,知道日志和编码
// Attach the business logic to the server
acceptor.setHandler(new TimeServerHandler());//数据接收发送处理类
// Configurate the buffer size and the iddle time
acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);//监听idle时间的,超过10秒自动断开会话
// And bind !
acceptor.bind(new InetSocketAddress(PORT));//绑定到9123端口
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.example.gettingstarted.timeserver;
import java.util.Date;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
* The Time Server handler : it return the current date when a message is
* received, or close the session if the "quit" message is received.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class TimeServerHandler extends IoHandlerAdapter {//该函数处理数据,当遇到quit时,断开会话。
/**
* 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 current date.
*/
@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;
}
// Send the current date back to the client
Date date = new Date();
session.write(date.toString());//把时间写入session内
System.out.println("Message written..." + str);
}
/**
* 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));
}
}
运行minaTimeServer,在命令行内容输入telnet 127.0.0.1 9123,输入信息,客户端输出你输入的信息。这就是简单的通信时间。