mina教程
关于mina介绍这里不做阐述.....
我们先做一个关于mina的helloworld
首先先下载mina包:http://mina.apache.org/ (如果你已经下载,此步骤忽略)
下载下来以后,我们主要是使用里面jar包
接下来打开eclipse,建立Java Project
引入jar包,根据官方文档提示:
我们所引入的jar文件为:
继续,开始写代码,我们先写一个server:
package org.xs.mina; 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) { //socket接收器 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() ); //设置读取数据缓存单位byte acceptor.getSessionConfig().setReadBufferSize( 2048 ); //设置多长时间后接收器开始空闲 acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 ); try { //绑定某个端口,作为数据入口 acceptor.bind( new InetSocketAddress(PORT) ); } catch (IOException e) { e.printStackTrace(); } } }
定义处理器:
package org.xs.mina; 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; 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; } System.out.println("my message>>>>>>>>>>"+str); Date date = new Date(); session.write( date.toString() ); } //会话空闲 @Override public void sessionIdle( IoSession session, IdleStatus status ) throws Exception { System.out.println( "IDLE " + session.getIdleCount( status )); } }
接下来,我们把server类,run起来,我们模拟下tcp调用,打开cmd命令行:C:\Users\xiao>telnet 127.0.0.1 9123
连接服务器,输入hello...
客户端:
服务端:
详细信息参考官方文档:http://mina.apache.org/mina-project/quick-start-guide.html