Apache 的Mina(Multipurpose Infrastructure Networked Applications)
是一个网络应用框架,可以帮助用户开发高性能和高扩展性的网络应用程序;它
提供了一个抽象的、事件驱动的异步API,使Java NIO 在各种传输协议(如
TCP/IP,UDP/IP 协议等)下快速高效开发。
---建个服务端和客户端试试
1.建立个服务端
public class Demo1Server {
private static int PORT = 3005;
private static Logger logger=Logger.getLogger(Demo1Server.class);
public static void main(String[] args) {
IoAcceptor acceptor = null;
try {
acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset
.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),
LineDelimiter.WINDOWS.getValue())));
//缓存大小
acceptor.getSessionConfig().setReadBufferSize(2048);
//空闲时间为10秒
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE , 10);
//绑定业务数据
acceptor.setHandler(new Demo1ServerHandler());
acceptor.bind(new InetSocketAddress(PORT));
logger.info("连接服务成功");
} catch (IOException e) {
logger.error("连接出错"+e.toString());
e.printStackTrace();
}
}
这里是业务处理
package com.itcast.service.imp;
import java.util.Date;
import org.apache.log4j.Logger;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
/**
* cong
* @author yt
*
*/
public class Demo1ServerHandler extends IoHandlerAdapter{
private static Logger logger=Logger.getLogger(Demo1ServerHandler.class);
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
super.exceptionCaught(session, cause);
logger.info("出错了..."+cause);
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
String msg=message.toString();
System.out.println(msg+" 接收消息...........");
if("bye".equals(msg))
{
session.close();
}
Date date=new Date();
session.write(date);
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
//这里设置发送消息后立即关掉服务与客户的连接
session.close();
logger.info("发送消息..........");
}
@Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
logger.info("服务关闭成功");
}
@Override
public void sessionCreated(IoSession session) throws Exception {
super.sessionCreated(session);
logger.info("服务与客户连接成功!");
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
super.sessionIdle(session, status);
logger.info("空闲时刻......");
}
@Override
public void sessionOpened(IoSession session) throws Exception {
super.sessionOpened(session);
logger.info("服务与客户端连接打开成功!");
}
}
---客户端测试
package com.itcast.client.demo;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.log4j.Logger;
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoConnector;
import org.apache.mina.common.IoSession;
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.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import com.itcast.client.demo.imp.MineClentHander;
public class MineClient1Demo {
/**
* @param args
* 这里涉及到长连接和短连接..........
*/
private static Logger log = Logger.getLogger(MineClient1Demo.class);
private static int PORT = 3005;
private static String URL = "10.2.15.19";
public static void main(String[] args) {
log.info("客户端测试........");
IoConnector connector = new NioSocketConnector();// 创建连接
connector.setConnectTimeout(30000);
//过滤utf-8
connector.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset
.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),
LineDelimiter.WINDOWS.getValue())));
connector.setHandler(new MineClentHander());
//业务处理
IoSession session=null;
try{
ConnectFuture fauter=connector.connect(new InetSocketAddress(URL, PORT));
fauter.awaitUninterruptibly();//等待创建连接完成
session=fauter.getSession();
session.write("君兽你是个怪兽");
}
catch(Exception ex)
{
log.error(ex.toString());
}
session.getCloseFuture().awaitUninterruptibly();//等待断开连接
connector.dispose();
}
}
--业务处理
package com.itcast.client.demo.imp;
import org.apache.log4j.Logger;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
public class MineClentHander extends IoHandlerAdapter{
private static Logger log=Logger.getLogger(MineClentHander.class);
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
log.error("客户端错误消息:"+cause);
super.exceptionCaught(session, cause);
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
String msg=message.toString();
log.info(msg+".........................客户端消息");
}
}