欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mina Io会话接口定义

程序员文章站 2024-01-12 21:58:40
...
Mina Nio处理器:http://donald-draper.iteye.com/blog/2377725
引言:
     前面的文章我们看了Nio处理器,先来回顾一下:
     NioProcessor内部有一个选择器Selector,一个可重入读写锁用于控制选择器相关的操作,构造主要是初始化线程执行器和选择器。Nio处理器的选择操作,唤醒等操作,实际通过内部的选择器完成。初始化会话,主要是配置会话通道为非阻塞模式,注册会话通道读事件到选择器。注册新选择器,主要是注册旧选择器的选择key(集合)关联的会话,通道,及通道兴趣事件集到新的选择器;会话时附加在通道选择key的Attachment上。处理器处理会话读写操作,主要是通过会话关联的通道完成。关闭会话主要是关闭会话关联的字节通道和取消会话关联选择key。
今天我们来看一下Io会话的定义:
/**
 * A handle which represents connection between two endpoints regardless of 
 * transport types.
 * 
 * {@link IoSession} provides user-defined attributes.  User-defined attributes
 * are application-specific data which is associated with a session.
 * It often contains objects that represents the state of a higher-level protocol
 * and becomes a way to exchange data between filters and handlers.
 * 
 * <h3>Adjusting Transport Type Specific Properties</h3>
 * <p>
 * You can simply downcast the session to an appropriate subclass.
 * 

 * 
 * <h3>Thread Safety</h3>
 * 
 * {@link IoSession} is thread-safe.  But please note that performing
 * more than one {@link #write(Object)} calls at the same time will
 * cause the {@link IoFilter#filterWrite(IoFilter.NextFilter, IoSession, IoFilter.WriteRequest)}
 * is executed simnutaneously, and therefore you have to make sure the
 * {@link IoFilter} implementations you're using are thread-safe, too. 
 * 

 *   
 * @author The Apache Directory Project (mina-dev@directory.apache.org)
 * @version $Rev$, $Date$
 */
public interface IoSession {

    /**
     * Returns the {@link IoService} which provides I/O service to this session.
     获取会话关联的IoService
     */
    IoService getService();

    /**
     * Returns the {@link IoServiceConfig} of this session.
     获取会话关联的IoService配置
     */
    IoServiceConfig getServiceConfig();

    /**
     * Returns the {@link IoHandler} which handles this session.
     获取会话Iohandler
     */
    IoHandler getHandler();

    /**
     * Returns the configuration of this session.
     获取会话配置
     */
    IoSessionConfig getConfig();

    /**
     * Returns the filter chain that only affects this session.
     获取会话过滤链
     */
    IoFilterChain getFilterChain();

    /**
     * Writes the specified <code>message</code> to remote peer.  This
     * operation is asynchronous; {@link IoHandler#messageSent(IoSession, Object)}
     * will be invoked when the message is actually sent to remote peer.
     * You can also wait for the returned {@link WriteFuture} if you want
     * to wait for the message actually written.
     发送消息给远端的peer。此操作是异步的,当消息实际发送到远端peer时,会调用
     IoHandler#messageSent方法法。如果想等待消息实际发送完,可以等待WriteFuture。
     */
    WriteFuture write(Object message);

    /**
     * Closes this session immediately.  This operation is asynthronous.
     * Wait for the returned {@link CloseFuture} if you want to wait for
     * the session actually closed.
     立刻关闭会话。此操作为异步的。如果想要等待会话实际完成关闭,可以等待CloseFuture
     */
    CloseFuture close();

    /**
     * Returns an attachment of this session.
     * This method is identical with <tt>getAttribute( "" )</tt>.
     返回会话附加物
     */
    Object getAttachment();

    /**
     * Sets an attachment of this session.
     * This method is identical with <tt>setAttribute( "", attachment )</tt>.
     * 设置会话附加物
     * @return Old attachment.  <tt>null</tt> if it is new.
     */
    Object setAttachment(Object attachment);

    /**
     * Returns the value of user-defined attribute of this session.
     * 获取会话属性key对一个的属性值
     * @param key the key of the attribute
     * @return <tt>null</tt> if there is no attribute with the specified key
     */
    Object getAttribute(String key);

    /**
     * Sets a user-defined attribute.
     * 设置会话属性
     * @param key the key of the attribute
     * @param value the value of the attribute
     * @return The old value of the attribute.  <tt>null</tt> if it is new.
     */
    Object setAttribute(String key, Object value);

    /**
     * Sets a user defined attribute without a value.  This is useful when
     * you just want to put a 'mark' attribute.  Its value is set to
     * {@link Boolean#TRUE}.
     * 设置会话无值属性
     * @param key the key of the attribute
     * @return The old value of the attribute.  <tt>null</tt> if it is new.
     */
    Object setAttribute(String key);

    /**
     * Removes a user-defined attribute with the specified key.
     * 移除会话属性
     * @return The old value of the attribute.  <tt>null</tt> if not found.
     */
    Object removeAttribute(String key);

    /**
     * Returns <tt>true</tt> if this session contains the attribute with
     * the specified <tt>key</tt>.
     判断是否包含属性key
     */
    boolean containsAttribute(String key);

    /**
     * Returns the set of keys of all user-defined attributes.
     获取会话所有属性
     */
    Set getAttributeKeys();

    /**
     * Returns transport type of this session.
     获取会话transport类型,socket,Datagram,vmpipe
     */
    TransportType getTransportType();

    /**
     * Returns <code>true</code> if this session is connected with remote peer.
     会话是否连接
     */
    boolean isConnected();

    /**
     * Returns <code>true</tt> if and only if this session is being closed
     * (but not disconnected yet) or is closed.
     会话是否关闭
     */
    boolean isClosing();

    /**
     * Returns the {@link CloseFuture} of this session.  This method returns
     * the same instance whenever user calls it.
     获取会话关闭结果
     */
    CloseFuture getCloseFuture();

    /**
     * Returns the socket address of remote peer. 
     获取会话远端peer地址
     */
    SocketAddress getRemoteAddress();

    /**
     * Returns the socket address of local machine which is associated with this
     * session.
     获取会话本地地址
     */
    SocketAddress getLocalAddress();

    /**
     * Returns the socket address of the {@link IoService} listens to to manage
     * this session.  If this session is managed by {@link IoAcceptor}, it
     * returns the {@link SocketAddress} which is specified as a parameter of
     * {@link IoAcceptor#bind(SocketAddress, IoHandler)}.  If this session is
     * managed by {@link IoConnector}, this method returns the same address with
     * that of {@link #getRemoteAddress()}.  
     获取IoService监听管理会话的地址。如果会话被IoAcceptor管理,返回的为IoAcceptor#bind(SocketAddress, IoHandler)
     的参数地址。如果会话为IoConnector,则返回的远端peer地址。
     */
    SocketAddress getServiceAddress();

    /**
     * Returns idle time for the specified type of idleness in seconds.
     返回空闲状态的空闲时间s
     */
    int getIdleTime(IdleStatus status);

    /**
     * Returns idle time for the specified type of idleness in milliseconds.
     返回空闲状态的空闲时间ms
     */
    long getIdleTimeInMillis(IdleStatus status);

    /**
     * Sets idle time for the specified type of idleness in seconds.
     设置空闲状态的空闲时间
     */
    void setIdleTime(IdleStatus status, int idleTime);

    /**
     * Returns write timeout in seconds.
     获取写超时时间s
     */
    int getWriteTimeout();

    /**
     * Returns write timeout in milliseconds.
     获取写超时时间ms
     */
    long getWriteTimeoutInMillis();

    /**
     * Sets write timeout in seconds.
     设置写超时时间
     */
    void setWriteTimeout(int writeTimeout);

    /**
     * Returns the current {@link TrafficMask} of this session.
     返回会话传输状态(读写)
     */
    TrafficMask getTrafficMask();

    /**
     * Sets the {@link TrafficMask} of this session which will result
     * the parent {@link IoService} to start to control the traffic
     * of this session immediately.
     设置会话传输状态,这将引起Io服务,开始控制会话传输
     */
    void setTrafficMask(TrafficMask trafficMask);

    /**
     * A shortcut method for {@link #setTrafficMask(TrafficMask)} that
     * suspends read operations for this session.
     暂定会话读操作
     */
    void suspendRead();

    /**
     * A shortcut method for {@link #setTrafficMask(TrafficMask)} that
     * suspends write operations for this session.
     暂定会话写操作
     */
    void suspendWrite();

    /**
     * A shortcut method for {@link #setTrafficMask(TrafficMask)} that
     * resumes read operations for this session.
     恢复会话读操作
     */
    void resumeRead();

    /**
     * A shortcut method for {@link #setTrafficMask(TrafficMask)} that
     * resumes write operations for this session.
     恢复会话写操作
     */
    void resumeWrite();

    /**
     * Returns the total number of bytes which were read from this session.
     获取从会话读取的字节数
     */
    long getReadBytes();

    /**
     * Returns the total number of bytes which were written to this session.
     获取会话写的字节数
     */
    long getWrittenBytes();

    /**
     * Returns the total number of messages which were read and decoded from this session. 
     获取从会话读取或解码的消息数
     */
    long getReadMessages();

    /**
     * Returns the total number of messages which were written and encoded by this session.
     获取会话发送消息和编码消息的数量
     */
    long getWrittenMessages();

    /**
     * Returns the total number of write requests which were written to this session.
     获取会话写请求的数量
     */
    long getWrittenWriteRequests();

    /**
     * Returns the number of write requests which are scheduled to be written
     * to this session.
     获取会话写请求实际被调度的数量,即实际发送数量
     */
    int getScheduledWriteRequests();

    /**
     * Returns the number of bytes which are scheduled to be written to this
     * session.
     获取会话实际发送字节数
     */
    int getScheduledWriteBytes();

    /**
     * Returns the time in millis when this session is created.
     获取会话创建时间
     */
    long getCreationTime();

    /**
     * Returns the time in millis when I/O occurred lastly.
     获取会话上一次发送IO操作的时间
     */
    long getLastIoTime();

    /**
     * Returns the time in millis when read operation occurred lastly.
    获取会话上一次读操作的时间
     */
    long getLastReadTime();

    /**
     * Returns the time in millis when write operation occurred lastly.
     获取会话上一次写操作的时间
     */
    long getLastWriteTime();

    /**
     * Returns <code>true</code> if this session is idle for the specified 
     * {@link IdleStatus}.
     判断会话是否处理空闲状态status
     */
    boolean isIdle(IdleStatus status);

    /**
     * Returns the number of the fired continuous <tt>sessionIdle</tt> events
     * for the specified {@link IdleStatus}.
     获取会话处于空闲状态status的次数
     * <p>
     * If <tt>sessionIdle</tt> event is fired first after some time after I/O,
     * <tt>idleCount</tt> becomes <tt>1</tt>.  <tt>idleCount</tt> resets to
     * <tt>0</tt> if any I/O occurs again, otherwise it increases to
     * <tt>2</tt> and so on if <tt>sessionIdle</tt> event is fired again without
     * any I/O between two (or more) <tt>sessionIdle</tt> events.
     */
    int getIdleCount(IdleStatus status);

    /**
     * Returns the time in millis when the last <tt>sessionIdle</tt> event
     * is fired for the specified {@link IdleStatus}.
     获取会话上次处于空闲状态status的时间
     */
    long getLastIdleTime(IdleStatus status);
}

附:
//TransportType
/**
 * Represents network transport types.
 * MINA provides three transport types by default:
 * [list]
 *   [*]{@link #SOCKET} - TCP/IP

 *   [*]{@link #DATAGRAM} - UDP/IP

 *   <li>{@link #VM_PIPE} - in-VM pipe support (only available in protocol
 *       layer</li>
 * [/list]
 * <p>
 * You can also create your own transport type.  Please refer to
 * {@link #TransportType(String[], boolean)}.
 * 
 * @author The Apache Directory Project (mina-dev@directory.apache.org)
 * @version $Rev$, $Date$
 */
public final class TransportType implements Serializable {
    private static final long serialVersionUID = 3258132470497883447L;

    private static final Map name2type = new HashMap();   
    private final String[] names;
    private final transient boolean connectionless;
    private final transient Class envelopeType;
    /**
     * Transport type: TCP/IP (Registry name: <tt>"SOCKET"</tt> or <tt>"TCP"</tt>)
     */
    public static final TransportType SOCKET = new TransportType(new String[] {
            "SOCKET", "TCP" }, false);

    /**
     * Transport type: UDP/IP (Registry name: <tt>"DATAGRAM"</tt> or <tt>"UDP"</tt>)
     */
    public static final TransportType DATAGRAM = new TransportType(
            new String[] { "DATAGRAM", "UDP" }, true);

    /**
     * Transport type: in-VM pipe (Registry name: <tt>"VM_PIPE"</tt>) 
     * Please refer to
     * [url=../protocol/vmpipe/package-summary.htm]<tt>org.apache.mina.protocol.vmpipe</tt>[/url]
     * package.
     */
    public static final TransportType VM_PIPE = new TransportType(
            new String[] { "VM_PIPE" }, Object.class, false);
    ...
 }


//TrafficMask
/**
 * A type-safe mask that is used to control the traffic of {@link IoSession}
 * with {@link IoSession#setTrafficMask(TrafficMask)}.
 *
 * @author The Apache Directory Project (mina-dev@directory.apache.org)
 * @version $Rev$, $Date$
 */
public class TrafficMask {
    private final int interestOps;
    private final String name;
    /**
     * This mask suspends both reads and writes.
     */
    public static final TrafficMask NONE = new TrafficMask(0, "none");

    /**
     * This mask suspends writes, and resumes reads if reads were suspended.
     */
    public static final TrafficMask READ = new TrafficMask(
            SelectionKey.OP_READ, "read");

    /**
     * This mask suspends reads, and resumes writes if writes were suspended.
     */
    public static final TrafficMask WRITE = new TrafficMask(
            SelectionKey.OP_WRITE, "write");

    /**
     * This mask resumes both reads and writes if any of them were suspended.
     */
    public static final TrafficMask ALL = new TrafficMask(SelectionKey.OP_READ
            | SelectionKey.OP_WRITE, "all");
    ...
 }
相关标签: mina