Apache Mina的最简单例子

apache mina的下载地址:[url]http://mina.apache.org/mina-project/downloads.html[/url]

1. 首先,要在classpath中配置以下的jar文件:
mina-core-2.0.7.jar
mina-example-2.0.7.jar
slf4j-api-1.6.6.jar
slf4j-log4j12-1.6.6.jar
log4j-1.2.17.jar

2. 基本要素:
1) IoFilters
2) codec: ProtocolCodecFactory
3) business logic: IoHandler

2. 基于TCP的服务例子:
1) 服务Server端
定义Server服务的代码

public class DemoTimeServer {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
final int PORT = 9123;

// 定义一个接收客户端请求的Acceptor
IoAcceptor acceptor = new NioSocketAcceptor();

// 1. 定义Logging的IoFilters
acceptor.getFilterChain().addLast("logger", new LoggingFilter());
// 2. 定义解析器的IoFilters,将客户端传入的流或协议数据按照定义的解析器进行解析
acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"))));

// 3. 设置业务处理机制,定义接收连接后的信息接收,信息回复的处理方法
acceptor.setHandler(new DemoTimeServerHandler());
//NioSocketAcceptor配置 acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

//定义完成,绑定端口
acceptor.bind(new InetSocketAddress(PORT));
}

}


定义处理Server端业务逻辑的代码

public class DemoTimeServerHandler implements IoHandler {

@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(true);
return;
}
Date date = new Date();
str = str + ", receiving date(" + date.toString() + ")";
session.write(str);
System.out.println("message write..." + str + ", writing date(" + date.toString());

}

@Override
public void messageSent(IoSession session, Object message) throws Exception {
String str = message.toString();
System.out.println("message sent..." + str);

}

@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("CLOSED " + session.getReadMessages());

}

@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("CREATED " + session.getCreationTime());

}

@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
System.out.println("IDEL " + session.getIdleCount(status));

}

@Override
public void sessionOpened(IoSession arg0) throws Exception {
// TODO Auto-generated method stub

}

}


2) 客户Client端
定义客户端链接服务端的代码

public class DemoTimeClient {

/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {

// 创建一个客户端连接
NioSocketConnector connector = new NioSocketConnector();

//1. 定义Logging的 IoFilters
connector.getFilterChain().addLast("logger", new LoggingFilter());
// 2.定义解析器的IoFilters,将发出的信息按照定义的解析器进行解析
connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"))));

// 3.设置业务处理机制,定义链接后的信息发送,接收回复信息的处理方法
DemoTimeClientHandler handler = new DemoTimeClientHandler("i am jeanjeanfang, hello dear!");
connector.setHandler(handler);

// 4. 链接服务端
IoSession session;
for (;;) {

try {

ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 9123));
future.awaitUninterruptibly();
session = future.getSession();
break;
} catch (RuntimeIoException e) {
System.err.println("Failed to connect.");
e.printStackTrace();
Thread.sleep(5000);
}
}

// wait until the summation is done
session.getCloseFuture().awaitUninterruptibly();

connector.dispose();

}

}



定义客户端和服务端链接后的业务代码

public class DemoTimeClientHandler extends IoHandlerAdapter {

private String message;

public DemoTimeClientHandler(String message){
this.message = message;
}

// 接收服务端的回复信息
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
System.out.println("message received..." + message.toString());
session.close(true);
}
// 打开连接后,将数据发送到服务端
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("session opened");
session.write(message);
}

@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
System.out.println("exception caught and close session");
session.close(true);
}

}



关于IoHandler(摘录自其它资料)
IoHandlerAdpater:
它只是提供了IoHandler中定义的方法体,没有任何的逻辑处理,你可以根据你自己的需求重写该类中的相关方法。这个类在实际的开发中使用的是较多的。我们上面写的例子都是继承于这个类来实现的。

SingleSessionIoHandlerDelegate:
这是一个服务器和客户端只有一个会话时使用的类,在该类的方法中没有提供session的参数,该类在实际的开发中使用的较少,如果需要对该类进行更深入的了解,请参考Mina 1.1.7的API文档。

在Mina提供的IoHandler的具体实现中,大部分的实现类都是继承与IoHandlerApater,IoHandlerAdpater在Mina 1.1.7中的子类有三个:

ChainedIoHandler:这个类主要是用于处理IoHandler的messageReceived事件,它和IoHandlerChain配合使用。当在业务逻辑中有多个IoHandler需要处理时,你可以将你的每个IoHandler添加到IoHandlerChain中,这个和过滤器
链比较相似,关于IoFilter和IoHandlerChain的具体用法和区别会在后续的文档中给出。

StreamIoHandler:该类也是用于处理IoHandler的messageReceived事件,它主要用于文件传输的系统中,比如FTP服务器中,如果需要对该类进行更深入的了解,请参考Mina 1.1.7的API文档。

DemuxingIoHandler:该类主要是用于处理多个IoHandler的messageReceived,由于在TCP/IP协议的数据传输中会出现数据的截断现象(由于socket传输的数据包的长度是固定的,当数据包大于该长度,数据包就会被截断),所以提供这个类主要是保证IoHandler所处理的数据包的完整性,这个和编解码器中的CumulativeProtocolDecoder类似,关于这两个类的具体介绍会在后续的文档中给出。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值