MINA示例

1.SERVER端程序和配置
程序 MinaServer.java:
package com.sillycat.manager.impl;


import java.net.InetSocketAddress;

import org.apache.mina.common.IoAcceptor;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

public class MinaServer {
private static final int SERVER_PORT = 8080;    
    
    public static void main( String[] args ) throws Throwable    
    {    
        IoAcceptor acceptor = new SocketAcceptor();    
            
        // Prepare the service configuration.    
        SocketAcceptorConfig cfg = new SocketAcceptorConfig();    
        cfg.setReuseAddress( true );    
   
        cfg.getFilterChain().addLast(    
                    "codec",    
                    new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) );    
        cfg.getFilterChain().addLast( "logger", new LoggingFilter() );    
   
        acceptor.bind(    
                new InetSocketAddress( SERVER_PORT ),    
                new MinaServerSessionHandler( ), cfg );    
        System.out.println( "The server Listening on port " + SERVER_PORT );    
    }    
}

SERVER端的处理类MinaServerSessionHandler.java:
package com.sillycat.manager.impl;

import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.util.SessionLog;
import com.sillycat.model.Message;

public class MinaServerSessionHandler extends IoHandlerAdapter {
public void sessionOpened(IoSession session) {
   // set idle time to 60 seconds
   session.setIdleTime(IdleStatus.BOTH_IDLE, 60);
   session.setAttribute("times", new Integer(0));
}

public void messageReceived(IoSession session, Object message) {
   System.out.println("in messageReceived");
   int times = ((Integer) (session.getAttribute("times"))).intValue();
   System.out.println("tiems = " + times);
   // communicate 30 times,then close the session.
   if (times < 1) {
    times++;
    session.setAttribute("times", new Integer(times));
    Message msg;
    msg = (Message) message;
    msg.setMsgBody("in server side: " + msg.getMsgBody());
    System.out.println("begin send msg: " + msg.getMsgBody());
    session.write(msg);
   } else {
    session.close();
   }
}
public void sessionIdle(IoSession session, IdleStatus status) {
   SessionLog.info(session, "Disconnecting the idle.");
   // disconnect an idle client
   session.close();
}
public void exceptionCaught(IoSession session, Throwable cause) {
   // close the connection on exceptional situation
   session.close();
}
}


2.CLIENT的程序和配置
CLIENT类MinaClient.java:
package com.sillycat.manager.impl;

import java.net.InetSocketAddress;

import org.apache.mina.common.IoSession;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.SocketConnector;
import org.apache.mina.transport.socket.nio.SocketConnectorConfig;

import com.sillycat.model.Message;

public class MinaClient {
private static final String HOSTNAME = "localhost";    
    private static final int PORT = 8080;    
    private static final int CONNECT_TIMEOUT = 30; // seconds    
   
   
    public static void main( String[] args ) throws Throwable    
    {    
        SocketConnector connector = new SocketConnector();            
        // Configure the service.    
        SocketConnectorConfig cfg = new SocketConnectorConfig();    
        cfg.setConnectTimeout( CONNECT_TIMEOUT );    
          cfg.getFilterChain().addLast(    
                    "codec",    
                    new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) );    
   
        cfg.getFilterChain().addLast( "logger", new LoggingFilter() );    
            
        IoSession session;    
        Message msg = new Message(0,1,"hello");    
        connector.connect(new InetSocketAddress( HOSTNAME, PORT ),    
                        new MinaClientSessionHandler(msg), cfg );    
   
    }   

}


CLIENT的实现类MinaClientSessionHandler.java:
package com.sillycat.manager.impl;

import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.util.SessionLog;

import com.sillycat.model.Message;

public class MinaClientSessionHandler extends IoHandlerAdapter {
private Object msg;

public MinaClientSessionHandler(Object msg) {
   this.msg = msg;
}

public void sessionOpened(IoSession session) {
   session.write(this.msg);
}

public void messageReceived(IoSession session, Object message) {
   System.out.println("in messageReceived!");
   Message rm = (Message) message;
   SessionLog.debug(session, rm.getMsgBody());
   System.out.println("message is: " + rm.getMsgBody());
   session.write(rm);
}

public void exceptionCaught(IoSession session, Throwable cause) {
   session.close();
}

}

你可能感兴趣的:(java,apache,.net,socket,Mina)