[size=medium]MINA框架的常用类 [/size]
类NioSocketAcceptor用于创建服务端监听;
类NioSocketConnector用于创建客户端连接;
类IoSession用来保存会话属性和发送消息;
类IoHandlerAdapter用于定义业务逻辑,常用的方法有:
方法 定义
sessionCreated() 当会话创建时被触发
sessionOpened() 当会话开始时被触发
sessionClosed() 当会话关闭时被触发
sessionIdle() 当会话空闲时被触发
exceptionCaught() 当接口中其他方法抛出异常未被捕获时触发此方法
messageRecieved() 当接收到消息后被触发
messageSent() 当发送消息后被触发
[size=medium]服务端应用开发示例 [/size]
所需jar包slf4j-api.jar、slf4j-jdk14.jar、MINA-core-2.0.0-M6.jar。
1)、首先定义一个业务逻辑处理器TimeServerHandler,继承自IoHandlerAdapter,实现的功能有:当客户端创建会话时会显示客户端设备的IP和端口;当客户端输入quit时结束会话;客户端输入其它内容时则向客户端发送当前时间。代码如下:
[b]TimeServerHandler :[/b]
[b]MinaTimeServer:[/b]
2)、客户端代码:
[b]TimeClientHandler:[/b]
[b]MinaTimeClient:[/b]
1)、建立两个工程代码组织如下:
[img]http://images.cnitblog.com/blog/302729/201302/18152106-6c3d51042a384e378da3e2630cfaaa55.jpg[/img]
[b]传输对象: [/b]
UserInfo:
[b]客户端代码:
ClientHandler:[/b]
[b]MainClient:[/b]
[b]服务器端:
ServerHandler:[/b]
[b]MainServer:[/b]
类NioSocketAcceptor用于创建服务端监听;
类NioSocketConnector用于创建客户端连接;
类IoSession用来保存会话属性和发送消息;
类IoHandlerAdapter用于定义业务逻辑,常用的方法有:
方法 定义
sessionCreated() 当会话创建时被触发
sessionOpened() 当会话开始时被触发
sessionClosed() 当会话关闭时被触发
sessionIdle() 当会话空闲时被触发
exceptionCaught() 当接口中其他方法抛出异常未被捕获时触发此方法
messageRecieved() 当接收到消息后被触发
messageSent() 当发送消息后被触发
[size=medium]服务端应用开发示例 [/size]
所需jar包slf4j-api.jar、slf4j-jdk14.jar、MINA-core-2.0.0-M6.jar。
1)、首先定义一个业务逻辑处理器TimeServerHandler,继承自IoHandlerAdapter,实现的功能有:当客户端创建会话时会显示客户端设备的IP和端口;当客户端输入quit时结束会话;客户端输入其它内容时则向客户端发送当前时间。代码如下:
[b]TimeServerHandler :[/b]
import java.util.Date;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
public class TimeServerHandler extends IoHandlerAdapter {
public void sessionCreated(IoSession session) {
// 显示客户端的ip和端口
System.out.println(session.getRemoteAddress().toString()+"1111111111111");
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
String str = message.toString();
System.out.println("str:"+str);
if (str.trim().equalsIgnoreCase("quit")) {
session.close();
// 结束会话return;
}
Date date = new Date();
session.write(date.toString());
// 返回当前时间的字符串
System.out.println("Message written..."+"2222222222");
}
}
[b]MinaTimeServer:[/b]
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
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 MinaTimeServer {
private static final int PORT = 9123;// 定义监听端口
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
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()); // 指定业务逻辑处理器
acceptor.setDefaultLocalAddress(new InetSocketAddress(PORT)); // 设置端口号
acceptor.bind();// 启动监听}
}
}
2)、客户端代码:
[b]TimeClientHandler:[/b]
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
public class TimeClientHandler extends IoHandlerAdapter{
public TimeClientHandler() {}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
System.out.println(message);// 显示接收到的消息
}
}
[b]MinaTimeClient:[/b]
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.future.ConnectFuture;
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;
public class MinaTimeClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// 创建客户端连接器.
NioSocketConnector connector = new NioSocketConnector();
connector.getFilterChain().addLast( "logger", new LoggingFilter() );
connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" )))); //设置编码过滤器
connector.setConnectTimeout(30);
connector.setHandler(new TimeClientHandler());//设置事件处理器
ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1", 9123));//建立连接
cf.awaitUninterruptibly();//等待连接创建完成
cf.getSession().write("hello");//发送消息
cf.getSession().write("quit");//发送消息
cf.getSession().getCloseFuture().awaitUninterruptibly();//等待连接断开
connector.dispose();
}
}
1)、建立两个工程代码组织如下:
[img]http://images.cnitblog.com/blog/302729/201302/18152106-6c3d51042a384e378da3e2630cfaaa55.jpg[/img]
[b]传输对象: [/b]
UserInfo:
package Mina.Object;
public class UserInfo implements java.io.Serializable{
private String name;
private String QQNum;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQQNum() {
return QQNum;
}
public void setQQNum(String qQNum) {
QQNum = qQNum;
}
}
[b]客户端代码:
ClientHandler:[/b]
package Mina.client;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import Mina.Object.UserInfo;
public class ClientHandler extends IoHandlerAdapter {
private static ClientHandler samplMinaClientHandler = null;
public static ClientHandler getInstances() {
if (null == samplMinaClientHandler) {
samplMinaClientHandler = new ClientHandler();
}
return samplMinaClientHandler;
}
private ClientHandler() {
}
public void sessionOpened(IoSession session) throws Exception {
session.write("客户端与服务器的会话打开了……");
UserInfo text=new UserInfo();
text.setName("梅竹寒香");
text.setQQNum("972341215");
session.write(text);
}
public void sessionClosed(IoSession session) {
}
public void messageReceived(IoSession session, Object message)
throws Exception {
}
public void messageSent(IoSession arg0, Object arg1) throws Exception {
System.out.println("客户端已经向服务器发送了:"+(String)arg1);
}
}
[b]MainClient:[/b]
package Mina.client;
import java.net.InetSocketAddress;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
public class MainClient {
private static MainClient mainClient = null;
NioSocketConnector connector = new NioSocketConnector();
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
public static MainClient getInstances() {
if (null == mainClient) {
mainClient = new MainClient();
}
return mainClient;
}
private MainClient() {
chain.addLast("myChin", new ProtocolCodecFilter(
new ObjectSerializationCodecFactory()));
connector.setHandler(ClientHandler.getInstances());
connector.setConnectTimeout(30);
ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",
8888));
}
public static void main(String args[]) {
MainClient.getInstances();
}
}
[b]服务器端:
ServerHandler:[/b]
package Mina.server;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import Mina.Object.UserInfo;
public class ServerHandler extends IoFilterAdapter implements IoHandler {
private static ServerHandler samplMinaServerHandler = null;
public static ServerHandler getInstances() {
if (null == samplMinaServerHandler) {
samplMinaServerHandler = new ServerHandler();
}
return samplMinaServerHandler;
}
private ServerHandler() {
}
// 当连接后打开时触发此方法,一般此方法与 sessionCreated 会被同时触发
public void sessionOpened(IoSession session) throws Exception {
}
public void sessionClosed(IoSession session) {
}
public void messageReceived(IoSession session, Object message)
throws Exception {
if (message instanceof UserInfo) {
UserInfo text = (UserInfo) message;
System.out.println("服务器接收到从客户端的姓名:"+text.getName());
System.out.println("服务器接收到从客户端的QQ:"+text.getQQNum());
}
}
public void exceptionCaught(IoSession arg0, Throwable arg1)
throws Exception {
}
// 当消息传送到客户端后触发
public void messageSent(IoSession arg0, Object arg1) throws Exception {
}
// 当一个新客户端连接后触发此方法.
public void sessionCreated(IoSession arg0) throws Exception {
}
// 当连接空闲时触发此方法.
public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
}
}
[b]MainServer:[/b]
package Mina.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
public class MainServer {
private static MainServer mainServer = null;
private SocketAcceptor acceptor = new NioSocketAcceptor();
private DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
private int bindPort = 8888;
public static MainServer getInstances() {
if (null == mainServer) {
mainServer = new MainServer();
}
return mainServer;
}
private MainServer() {
chain.addLast("myChin", new ProtocolCodecFilter(
new ObjectSerializationCodecFactory()));
acceptor.setHandler(ServerHandler.getInstances());
try {
acceptor.bind(new InetSocketAddress(bindPort));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
MainServer.getInstances();
}
}