如何使用Java的网络库Mina
mina 这个网络资源包,是通过重写了CumulativeProtocolDecoder 中的doDecoded 方法中的Iosession对象。然后对方法事事的监测,在这个方法里面加上需要监测的函数。
(1)package mina.client;import java.net.InetSocketAddress;import java.nio.charset.Charset;import java.util.Scanner;import mina.common.BaseConfig;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.prefixedstring.PrefixedStringCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketConnector;public class MinaTimeClient { public static void main(String[] args) { //用于TCP/TP连接的NioSocketConnector类 IoConnector connector = new NioSocketConnector(); //增加日志过滤链 connector.getFilterChain().addLast("logger", new LoggingFilter()); //增加协议过滤链,一个Filter用于转换二进制数据或者特定的协议数据为消息对象 connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset .forName("UTF-8")))); //设置会处理所有被service管理的连接的handler connector.setHandler(new TimeClientHander()); //连接到特定的remote地址,InetSocketAddress封装IP和port,Java网络编程规范, //不提供直接的ip地址和端口的connect方法 ConnectFuture connectFuture = connector.connect(new InetSocketAddress( "127.0.0.1", BaseConfig.PORT)); // 等待建立连接 connectFuture.awaitUninterruptibly(); System.out.println("连接成功"); //返回代表两端连接的一个对象,有读写方法以及获取本端网络设置的相关方法 IoSession session = connectFuture.getSession(); Scanner sc = new Scanner(System.in); boolean quit = false; //一直读取输入,并发送到对端(服务端),直到输入quit while (!quit) { String str = sc.next(); if (str.equalsIgnoreCase("quit")) { quit = true; }//利用session写出数据 session.write(str); } // 关闭 if (session != null) { if (session.isConnected()) { session.getCloseFuture().awaitUninterruptibly(); } //Releases any resources allocated by this service connector.dispose(true); } }}
(2)package mina.client;import org.apache.mina.core.service.IoHandler;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;/** * service所绑定的handler,当手打送消息或者发送消息等等事件发生的时候 * 就会首先触发这里的方法 * IoHandler Handles all I/O events fired by MINA. */public class TimeClientHander implements IoHandler { @Override public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception { // TODO Auto-generated method stub arg1.printStackTrace(); } @Override public void messageReceived(IoSession arg0, Object message) throws Exception { // TODO Auto-generated method stub System.out.println("client接受信息:" + message.toString()); } @Override public void messageSent(IoSession arg0, Object message) throws Exception { // TODO Auto-generated method stub System.out.println("client发送信息" + message.toString()); } @Override public void sessionClosed(IoSession session) throws Exception { // TODO Auto-generated method stub System.out.println("client与:" + session.getRemoteAddress().toString() + "断开连接"); } @Override public void sessionCreated(IoSession session) throws Exception { // TODO Auto-generated method stub System.out.println("client与:" + session.getRemoteAddress().toString() + "建立连接"); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { // TODO Auto-generated method stub System.out.println("IDLE " + session.getIdleCount(status)); } @Override public void sessionOpened(IoSession arg0) throws Exception { // TODO Auto-generated method stub System.out.println("打开连接"); }}
(3)package mi
(3)package mina.common;
public class BaseConfig {
// 服务器端口public static final int PORT = 9123;}package mina.server;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.charset.Charset;import mina.common.BaseConfig;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.prefixedstring.PrefixedStringCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;public class MinaTimeServer {private static final int PORT = BaseConfig.PORT;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 PrefixedStringCodecFactory(Charset.forName("UTF-8"))));acceptor.setHandler(new TimeServerHandler());/*Sets the size of the read buffer that I/O processor allocates* per each read. It's unusual to adjust this property because* it's often adjusted automatically by the I/O processor* 一次最多读取这么多字节,不足也返回*/acceptor.getSessionConfig().setReadBufferSize(2048);//设置空转时间acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);acceptor.bind(new InetSocketAddress(PORT));}}
na.common;
public class BaseConfig {
// 服务器端口public static final int PORT = 9123;}package mina.server;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.charset.Charset;import mina.common.BaseConfig;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.prefixedstring.PrefixedStringCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;public class MinaTimeServer {private static final int PORT = BaseConfig.PORT;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 PrefixedStringCodecFactory(Charset.forName("UTF-8"))));acceptor.setHandler(new TimeServerHandler());/*Sets the size of the read buffer that I/O processor allocates* per each read. It's unusual to adjust this property because* it's often adjusted automatically by the I/O processor* 一次最多读取这么多字节,不足也返回*/acceptor.getSessionConfig().setReadBufferSize(2048);//设置空转时间acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);acceptor.bind(new InetSocketAddress(PORT));}}
(4)package mina.server;import java.util.Date;import org.apache.mina.core.service.IoHandler;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;public class TimeServerHandler implements IoHandler { @Override public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception { arg1.printStackTrace(); } @Override public void messageReceived(IoSession session, Object message) throws Exception { String str = message.toString(); System.out.println("接受到的消息:" + str); if (str.trim().equalsIgnoreCase("quit")) { session.close(true); return; } Date date = new Date(); session.write(date.toString()); System.out.println("Message written..."); } @Override public void messageSent(IoSession arg0, Object arg1) throws Exception { // TODO Auto-generated method stub System.out.println("发送信息:" + arg1.toString()); } @Override public void sessionClosed(IoSession session) throws Exception { // TODO Auto-generated method stub System.out.println("IP:" + session.getRemoteAddress().toString() + "断开连接"); } @Override public void sessionCreated(IoSession session) throws Exception { // TODO Auto-generated method stub System.out.println("IP:" + session.getRemoteAddress().toString()); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { // TODO Auto-generated method stub System.out.println("IDLE " + session.getIdleCount(status)); } @Override public void sessionOpened(IoSession arg0) throws Exception { // TODO Auto-generated method stub }}