转自http://javasight.net/2011/05/simple-client-server-application-using-mina/
[size=large]Introduction介绍[/size]
Mina的缩写意思是”Multipurpose Infrastructure for Network Applications(多用途网络应用基础设施)”,它用于开发高度可扩展和高性能网络应用的网络应用框架。在本文中,让我们看看如何使用Apache Mina2.0.x来创建一个简单的客户端服务器端(c/s)应用。
[b]所需的JAR包[/b]
Apache Mina 2.0.x jars
slf4j-api.jar
slf4k-jdk14.jar
[size=large]服务端部分[/size]
对服务器端部分,我们需要使用MinaServer和MinaServerHandler两个类。MinaServer类包含了主方法和名为IoAcceptor的借口来接受来自客户端的进入连接,IoAcceptor用于向handler触发相应的事件。 我们使用了两个过滤器,第一个是LoggingFilter,用于记录所有的事件,第二个是ProtocolCOdecFilter,用于转换进入的ByteBuffer到报文的POJO。MinaServer的类代码如下:
MinaServer.java
接着我们创建一个名为MinaServerHandler自定义handler,它包含了4个方法。第一个方法是sessionOpened在session打开后被调用, 它用于设置session的空闲时间。第二个方法是receiveMessage,用于接收由客户端发送的消息。 其他两个方法sessionIdle用于在session空闲10秒钟后关闭该session,第四个方法exceptionCaught用于在异常发生时关闭session。MinaServerHandler类的代码如下:
MinaServerHandler.java
[size=large]客户端部分[/size]
对于客户端部分MinaClient和MinaClientHandler类被我们所使用。在MinaClient类中,IoConnector借口用于与服务器端进行交互并向handler中触发事件。 向服务端一样,同样的LoggingFilter、ProtocolCodecFilter也被使用了。名为ConnectFuture接口被用于处理异步的连接请求。MinaClient类代码如下:
MinaClient.java
对于handler,像服务器部分一样,sessionOpened、messageReceived和exceptionCaught方法同样被使用了。MinaClientHandler类代码如下:
MinaClientHandler.java
现在是对之前代码进行测试的时候了,首先MinaServer应该先被启动然后启动MinaClient,代码的输出类似如下:
[b]MinaServer – 输出[/b]
[b]MinaClient – 输出[/b]
这就是所有内容。我希望本文清晰的解释了使用Apache Mina 2.0.x的简单的客户端/服务器应用。
[size=large]Introduction介绍[/size]
Mina的缩写意思是”Multipurpose Infrastructure for Network Applications(多用途网络应用基础设施)”,它用于开发高度可扩展和高性能网络应用的网络应用框架。在本文中,让我们看看如何使用Apache Mina2.0.x来创建一个简单的客户端服务器端(c/s)应用。
[b]所需的JAR包[/b]
Apache Mina 2.0.x jars
slf4j-api.jar
slf4k-jdk14.jar
[size=large]服务端部分[/size]
对服务器端部分,我们需要使用MinaServer和MinaServerHandler两个类。MinaServer类包含了主方法和名为IoAcceptor的借口来接受来自客户端的进入连接,IoAcceptor用于向handler触发相应的事件。 我们使用了两个过滤器,第一个是LoggingFilter,用于记录所有的事件,第二个是ProtocolCOdecFilter,用于转换进入的ByteBuffer到报文的POJO。MinaServer的类代码如下:
MinaServer.java
package net.javasight.mina;
/**
* @author javasight
*/
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.service.IoAcceptor;
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 MinaServer {
private static final int PORT = 1234;
public static void main(String[] args) throws IOException {
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 MinaServerHandler());
acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
acceptor.bind(new InetSocketAddress(PORT));
}
}
接着我们创建一个名为MinaServerHandler自定义handler,它包含了4个方法。第一个方法是sessionOpened在session打开后被调用, 它用于设置session的空闲时间。第二个方法是receiveMessage,用于接收由客户端发送的消息。 其他两个方法sessionIdle用于在session空闲10秒钟后关闭该session,第四个方法exceptionCaught用于在异常发生时关闭session。MinaServerHandler类的代码如下:
MinaServerHandler.java
package net.javasight.mina;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
* @author javasight
*/
public class MinaServerHandler extends IoHandlerAdapter {
private final Logger logger = Logger.getLogger(getClass());
@Override
public void sessionOpened(IoSession session) {
// set idle time to 10 seconds
session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
session.setAttribute("Values: ");
}
@Override
public void messageReceived(IoSession session, Object message) {
logger.info("Message received in the server..");
logger.info("Message is: " + message.toString());
}
@Override
public void sessionIdle(IoSession session, IdleStatus status) {
logger.info("Disconnecting the idle.");
// disconnect an idle client
session.close();
}
@Override
public void exceptionCaught(IoSession session, Throwable cause) {
// close the connection on exceptional situation
session.close();
}
}
[size=large]客户端部分[/size]
对于客户端部分MinaClient和MinaClientHandler类被我们所使用。在MinaClient类中,IoConnector借口用于与服务器端进行交互并向handler中触发事件。 向服务端一样,同样的LoggingFilter、ProtocolCodecFilter也被使用了。名为ConnectFuture接口被用于处理异步的连接请求。MinaClient类代码如下:
MinaClient.java
package net.javasight.mina;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
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.NioSocketConnector;
/**
* @author javasight
*/
public class MinaClient {
private static final int PORT = 1234;
public static void main(String[] args) throws IOException,
InterruptedException {
IoConnector connector = new NioSocketConnector();
connector.getSessionConfig().setReadBufferSize(2048);
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset
.forName("UTF-8"))));
connector.setHandler(new MinaClientHandler("Hello Server.."));
ConnectFuture future = connector.connect(new InetSocketAddress(
"172.108.0.12", PORT));
future.awaitUninterruptibly();
if (!future.isConnected()) {
return;
}
IoSession session = future.getSession();
session.getConfig().setUseReadOperation(true);
session.getCloseFuture().awaitUninterruptibly();
System.out.println("After Writing");
connector.dispose();
}
}
对于handler,像服务器部分一样,sessionOpened、messageReceived和exceptionCaught方法同样被使用了。MinaClientHandler类代码如下:
MinaClientHandler.java
package net.javasight.mina;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
/**
* @author giftsam
*/
public class MinaClientHandler extends IoHandlerAdapter {
private final Logger logger = Logger.getLogger(getClass());
private final String values;
private boolean finished;
public MinaClientHandler(String values) {
this.values = values;
}
public boolean isFinished() {
return finished;
}
@Override
public void sessionOpened(IoSession session) {
session.write(values);
}
@Override
public void messageReceived(IoSession session, Object message) {
logger.info("Message received in the client..");
logger.info("Message is: " + message.toString());
}
@Override
public void exceptionCaught(IoSession session, Throwable cause) {
session.close();
}
}
现在是对之前代码进行测试的时候了,首先MinaServer应该先被启动然后启动MinaClient,代码的输出类似如下:
[b]MinaServer – 输出[/b]
4412 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - CREATED
4412 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - OPENED
4449 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - RECEIVED: HeapBuffer[pos=0 lim=15 cap=2048: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 0A]
0 [NioProcessor-2] INFO net.javasight.mina.MinaServerHandler - Message received in the server..
1 [NioProcessor-2] INFO net.javasight.mina.MinaServerHandler - Message is: Hello Server..
14453 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - IDLE
10001 [NioProcessor-2] INFO net.javasight.mina.MinaServerHandler - Disconnecting the idle.
14457 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - CLOSED
[b]MinaClient – 输出[/b]
297 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - CREATED
297 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - OPENED
325 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - SENT: HeapBuffer[pos=0 lim=0 cap=0: empty]
10334 [NioProcessor-2] INFO org.apache.mina.filter.logging.LoggingFilter - CLOSED
After Writing
这就是所有内容。我希望本文清晰的解释了使用Apache Mina 2.0.x的简单的客户端/服务器应用。