(一)

package testMina;

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.transport.socket.nio.NioSocketAcceptor; public class MinaSimpleServer {
private static final int PORT = 9123;
private static final String HOST = "localhost"; public static void main(String[] args) {
// 接收者
IoAcceptor acceptor = new NioSocketAcceptor();
// 设置编码器
acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
// 设置Handler
acceptor.setHandler(new TimeServerHandler());
// 心跳
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 6);
// 绑定端口,启动服务,并开始处理远程客户端请求
try {
acceptor.bind(new InetSocketAddress(HOST, PORT));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("服务端启动成功");
}
}

(二)

package testMina;

import java.sql.Timestamp;
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 {
private int count = 0; // 由底层决定是否创建一个session
@Override
public void sessionCreated(IoSession session) {
System.out.println("新的连接");
} // 创建了session 后会回调sessionOpened
public void sessionOpened(IoSession session) throws Exception {
count++;
System.out.println("第 " + count + " 个 client 登陆!address: : " + session.getRemoteAddress());
} // 有异常时执行方法
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
System.out.println("客户端断了!!!");
//cause.printStackTrace();
} //接收消息时调用
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
String str = message.toString();
System.out.println("接受到的数据是:" + message);
if (str.trim().equalsIgnoreCase("quit")) {
session.close();
return;
}
Date date = new Date();
// 向输出流中写东西
session.write(date.toString());
System.out.println("Message written...");
}
// session 关闭调用
@Override
public void sessionClosed(IoSession session) {
System.out.println("one client disconnect");
session.close(session.isConnected());
} // 当连接空闲时触发此方法.
@Override
public void sessionIdle(IoSession session, IdleStatus status) {
System.out.println("【时间】:"+new Timestamp(System.currentTimeMillis())+"连接空闲(心跳机制)");
} // 当信息已经传送给客户端后触发此方法.
@Override
public void messageSent(IoSession session, Object message) {
System.out.println("信息已经传送给客户端");
}
}
05-21 16:44