Mina学习笔记(2) HelloWorld(TCP/IP)

这里来写一个简单的基于 TCP/IP 协议的c-s 实例

1、引入相关jar包,只需引入mina-core.jar 和 log4j 及相关实现包即可

这里是mina所需jar包及其下载地址

  • MINA 2.x Core
  • JDK 1.5 or greater
  • SLF4J 1.3.0 or greater
    • Log4J 1.2 users: slf4j-api.jar, slf4j-log4j12.jar, and Log4J 1.2.x
    • Log4J 1.3 users: slf4j-api.jar, slf4j-log4j13.jar, and Log4J 1.3.x
    • java.util.logging users: slf4j-api.jar and slf4j-jdk14.jar

     mina下载地址:http://mina.apache.org/downloads-mina.html

    log4j                   http://www.slf4j.org/download.html

    这里确保log4j和slf4j版本一致

    如果您用maven作为项目管理插件的话可以这样




  • <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>mina</groupId>
    	<artifactId>mina</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<dependencies>
    		<dependency>
    			<groupId>org.apache.mina</groupId>
    			<artifactId>mina-core</artifactId>
    			<version>2.0.7</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-api</artifactId>
    			<version>1.5.8</version>
    		</dependency>
    		<dependency>
    			<groupId>log4j</groupId>
    			<artifactId>log4j</artifactId>
    			<version>1.2.14</version>
    		</dependency>
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-log4j12</artifactId>
    			<version>1.5.8</version>
    		</dependency>
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>jcl-over-slf4j</artifactId>
    			<version>1.5.8</version>
    		</dependency>
    	</dependencies>
    </project>
     编写server 
    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.LineDelimiter;
    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 = 9725;
    	public static void main(String[] args) throws Exception{
    		// 创建一个非阻塞的server端的Socket,因为这里是服务端所以用IoAcceptor
    		IoAcceptor acceptor = new NioSocketAcceptor();
    		// 添加一个日志过滤器
    		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    		// 添加一个编码过滤器
    		acceptor.getFilterChain().addLast("codec",
    				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),
    						LineDelimiter.WINDOWS.getValue(),
    						LineDelimiter.WINDOWS.getValue())));
    
    		// 绑定业务处理器,这段代码要在acceptor.bind()方法之前执行,因为绑定套接字之后就不能再做这些准备
    		acceptor.setHandler(new MinaServerHanlder());
    		// 设置读取数据的缓冲区大小
    		acceptor.getSessionConfig().setReadBufferSize(2048);
    		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
    		// 绑定一个监听端口
    		acceptor.bind(new InetSocketAddress(PORT));
    	}
    }
    
    server 业务处理类
    import java.util.Date;
    
    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;
    
    public class MinaServerHanlder extends IoHandlerAdapter {
    	public static Logger logger = Logger.getLogger(MinaServerHanlder.class);
    	@Override
    	public void exceptionCaught(IoSession session, Throwable cause)throws Exception {
    		cause.printStackTrace();
    	}
    
    	@Override
    	public void messageReceived(IoSession session, Object message)throws Exception {
    		 String str = message.toString();
    	        if( str.trim().equalsIgnoreCase("quit") ) {
    	            session.close(Boolean.TRUE);
    	            return;
    	        }
    	        Date date = new Date();
    	        session.write( date.toString() );
    		logger.info("server -消息已经接收到!"+message);
    	}
    
    	@Override
    	public void messageSent(IoSession session, Object message) throws Exception {
    		logger.info("server -消息已经发出");
    	}
    
    	@Override
    	public void sessionClosed(IoSession session) throws Exception {
    		logger.info("server-session关闭连接断开");
    	}
    
    	@Override
    	public void sessionCreated(IoSession session) throws Exception {
    		logger.info("server-session创建,建立连接");
    	}
    
    	@Override
    	public void sessionIdle(IoSession session, IdleStatus status)throws Exception {
    		logger.info("server-服务端进入空闲状态..");
    	}
    
    	@Override
    	public void sessionOpened(IoSession session) throws Exception {
    		logger.info("server-服务端与客户端连接打开...");
    	}
    }
    
    import java.net.InetSocketAddress;
    import java.nio.charset.Charset;
    
    import org.apache.log4j.Logger;
    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.LineDelimiter;
    import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
    import org.apache.mina.transport.socket.nio.NioSocketConnector;
    
    
    public class MinaClient {
    	private static Logger log = Logger.getLogger(MinaClient.class);
    	private static String HOST="localhost";
    	private static int PORT=9725;
    	public static void main(String[] args) {
    		IoConnector conn = new NioSocketConnector();
    		// 设置链接超时时间
    		conn.setConnectTimeoutMillis(30000L);
    		// 添加过滤器
    		conn.getFilterChain().addLast("codec",
    				        new ProtocolCodecFilter(new TextLineCodecFactory(Charset
    						.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),
    						LineDelimiter.WINDOWS.getValue())));
    		// 添加业务处理handler
    		conn.setHandler(new MinaClientHandler()); 
    		IoSession session =null;
    		try {
    			ConnectFuture future = conn.connect(new InetSocketAddress(HOST, PORT));// 创建连接
    			future.awaitUninterruptibly();// 等待连接创建完成
    			session = future.getSession();// 获得session
    			session.write("Hello World!");// 发送消息
    		} catch (Exception e) {
    			log.error("客户端链接异常...", e);
    		}
    
    		session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
    		conn.dispose();
    
    	}
    }
    
    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;
    
    public class MinaClientHandler extends  IoHandlerAdapter {
    	private static final Logger log = Logger.getLogger(MinaClientHandler.class);
    	@Override
    	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    		cause.printStackTrace();
    	}
    
    	@Override
    	public void messageReceived(IoSession session, Object message)throws Exception {
    		log.info("client消息接收到"+message);
    	}
    
    	@Override
    	public void messageSent(IoSession session, Object message) throws Exception {
    		log.info("client-消息已经发送"+message);
    	}
    
    	@Override
    	public void sessionClosed(IoSession session) throws Exception {
    		log.info("client -session关闭连接断开");
    	}
    
    	@Override
    	public void sessionCreated(IoSession session) throws Exception {
    		System.out.println("client -创建session");
    	}
    
    	@Override
    	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    		System.out.println("client-系统空闲中...");
    	}
    
    	@Override
    	public void sessionOpened(IoSession session) throws Exception {
    		System.out.println("client-session打开");
    	}
    }
    
  • 先运行server在运行client’ 结果