⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 reliableinputstream.java

📁 jxta平台的开发包
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * $Id: ReliableInputStream.java,v 1.23 2006/05/30 20:58:27 hamada Exp $ * * Copyright (c) 2003 Sun Microsystems, Inc.  All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright *    notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright *    notice, this list of conditions and the following disclaimer in *    the documentation and/or other materials provided with the *    distribution. * * 3. The end-user documentation included with the redistribution, *    if any, must include the following acknowledgment: *       "This product includes software developed by the *       Sun Microsystems, Inc. for Project JXTA." *    Alternately, this acknowledgment may appear in the software itself, *    if and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" *    must not be used to endorse or promote products derived from this *    software without prior written permission. For written *    permission, please contact Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", *    nor may "JXTA" appear in their name, without prior written *    permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED.  IN NO EVENT SHALL SUN MICROSYSTEMS OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of Project JXTA.  For more * information on Project JXTA, please see * <http://www.jxta.org/>. * * This license is based on the BSD license adopted by the Apache Foundation. */package net.jxta.impl.util.pipe.reliable;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InterruptedIOException;import java.net.SocketTimeoutException;import java.util.ArrayList;import java.util.Arrays;import java.util.Iterator;import java.util.List;import net.jxta.endpoint.ByteArrayMessageElement;import net.jxta.endpoint.Message;                                     import net.jxta.endpoint.MessageElement;import net.jxta.endpoint.WireFormatMessageFactory;import net.jxta.impl.util.TimeUtils;import org.apache.log4j.Level;import org.apache.log4j.Logger;/** *  Acts as a reliable input stream. Accepts data which *  arrives in messages and orders it. */public class ReliableInputStream extends InputStream implements Incoming {    private static final Logger LOG =        Logger.getLogger(ReliableInputStream.class.getName());    private static final boolean  DEBUGIO = false;    /**     *  Connection we are working for.     */    private Outgoing outgoing;    private volatile boolean closed = false;    private boolean closing = false;    private Record record = null;    private MsgListener listener = null;    private int timeout;    private volatile int sequenceNumber = 0;    // Incoming messages queue    private List inputQueue = new ArrayList();    /**     * Input record Object     */    private static class Record {        public InputStream inputStream;        // next inbuff byte        public long nextByte;        // size of Record        public long size;        public Record() {            inputStream = null; // allocated by caller            nextByte = 0;  // We read here (set by caller)            size = 0;   // Record size(set by caller)        }        /** reset the record element         *         */        public void resetRecord() {            if (null != inputStream) {                try {                    inputStream.close();                } catch (IOException ignored) {}            }            inputStream = null;            size = nextByte = 0;        }    }    // An input queue element which breaks out a    // received message in enqueueMessage().    private static class IQElt implements Comparable {        int seqnum;        MessageElement elt;        boolean ackd;            public boolean equals(Object obj) {            if (this == obj) {                return true;            }            if (obj instanceof IQElt) {                IQElt targ = (IQElt) obj;                return (this.seqnum == targ.seqnum);            }            return false;        }        public int compareTo(IQElt el)  {            return this.seqnum < el.seqnum ? -1 : this.seqnum == el.seqnum ? 0 : 1;        }        public int compareTo(Object o) {            return compareTo((IQElt)o);        }    }    public ReliableInputStream(Outgoing outgoing, int timeout) {        this(outgoing, timeout, null);    }    public ReliableInputStream(Outgoing outgoing, int timeout, MsgListener listener) {        if (timeout < 0) {            throw new IllegalArgumentException("Can not specify timeout < 0");        }        this.outgoing = outgoing;        if (timeout == 0) {            timeout = Integer.MAX_VALUE;        }        this.timeout = timeout;        record = new Record();        this.listener = listener;        // 1 <= seq# <= maxint, monotonically increasing        //  Incremented before compare.        sequenceNumber = 0;        if (LOG.isEnabledFor(Level.INFO)) {            if (listener != null) {                LOG.info("Listener based ReliableInputStream created");            }        }    }    /**     * {@inheritDoc}     */    public void close() throws IOException {        super.close();        synchronized (inputQueue) {            closed = true;            inputQueue.clear();            inputQueue.notifyAll();        }    }    /**     * Returns true if closed     * @return true if closed     */     public boolean isInputShutdown() {         return closed;     }    /**     * prepare this input stream to being closed. It will still     * deliver the packets that have been received, but nothing     * more. This is meant to be called in response to the other side     * having initiated closure. We assume that when the other side does it     * it means that it is satified with what we have acknoleged so far.     */    public void setClosing() throws IOException {        synchronized (inputQueue) {            closing = true;            inputQueue.notifyAll();        }    }    /**     *  Sets the Timeout attribute. A timeout of 0 blocks forever     *     * @param  timeout The new soTimeout value     */    public void setTimeout(int timeout) {        synchronized (inputQueue) {            this.timeout = timeout;        }    }        /**     * {@inheritDoc}     */    public int read() throws IOException {        if (closed) {            return -1;        }        byte[] a = new byte[1];        while (true) {            int len = local_read( a, 0, 1 );            if (len < 0) {                break;            }            if (len > 0) {                if (DEBUGIO && LOG.isEnabledFor(Level.DEBUG)) {                    LOG.debug("Read() : " + (int) (a[0] & 0xFF));                }                return (int) (a[0] & 0xFF); // The byte            }        }        // If we've reached EOF, there's nothing to do but close().        close();        return -1;    }    /**     * {@inheritDoc}     */    public int read(byte[] a, int offset, int length) throws IOException {        if (closed) {            return -1;        }        if (0 == length) {            return 0;        }        int i = local_read(a, offset, length);        if (DEBUGIO && LOG.isEnabledFor(Level.DEBUG)) {            LOG.debug("Read(byte[], int, " + length + "), bytes read = " + i);        }        // If we've reached EOF; there's nothing to do but close().        if (i == -1) {            close();        }        return i;    }    /**     *  Send a sequential ACK and selective ACKs for all of     *  the queued messages.     *     *  @param seqnAck the sequence number being sequential ACKed     */    private void sendACK(int seqnAck) {        //No need to sync on inputQueue, acking as many as we can is want we want        List selectedAckList = new ArrayList();        List queue;        synchronized(inputQueue) {            queue = Arrays.asList(inputQueue.toArray());        }        Iterator eachInQueue = queue.iterator();            while (eachInQueue.hasNext() &&                   (selectedAckList.size() < Defs.MAXQUEUESIZE)) {                IQElt anIQElt = (IQElt) eachInQueue.next();                if (anIQElt.seqnum > seqnAck) {                    if (!anIQElt.ackd) {                        selectedAckList.add(new Integer(anIQElt.seqnum));                        anIQElt.ackd = true;                    }                }        }        // PERMIT DUPLICATE ACKS. Just a list and one small message.        sendACK(seqnAck, selectedAckList);    }    /**     *  Build an ACK message. The message provides a sequential ACK count and     *  an optional list of selective ACKs.     *     *  @param seqnAck the sequence number being sequential ACKed     *  @param sackList a list of selective ACKs. Must be sorted in increasing     *  order.     */    private void sendACK(int seqnAck, List sackList) {        ByteArrayOutputStream bos =            new ByteArrayOutputStream((1 + sackList.size()) * 4);        DataOutputStream dos = new DataOutputStream(bos);        try {            dos.writeInt(seqnAck);            Iterator eachSACK = sackList.iterator();            while(eachSACK.hasNext()) {                int aSack = ((Integer)eachSACK.next()).intValue();                dos.writeInt(aSack);            }            dos.close();            bos.close();            Message ACKMsg = new Message();            MessageElement elt =                new ByteArrayMessageElement(Defs.ACK_ELEMENT_NAME,                                            Defs.MIME_TYPE_ACK,                                            bos.toByteArray(), null);            ACKMsg.addMessageElement(Defs.NAMESPACE, elt);            outgoing.send(ACKMsg);            if (LOG.isEnabledFor(Level.DEBUG)) {                LOG.debug("SENT ACK, seqn#" + seqnAck +                         " and " + sackList.size() + " SACKs ");            }        } catch (IOException e) {            if (LOG.isEnabledFor(Level.WARN)) {                LOG.warn("sendACK caught IOException:", e);            }        }    }    public void recv(Message msg) {        queueIncomingMessage(msg);    }    public boolean hasNextMessage() {        return !inputQueue.isEmpty();    }    public synchronized Message nextMessage()    throws IOException {        return nextMessage(true);    }    private Message nextMessage(boolean blocking) throws IOException  {        if (LOG.isEnabledFor(Level.DEBUG)) {            LOG.debug("nextMessage blocking?  ["+blocking+"]");        }        MessageElement elt = dequeueMessage(sequenceNumber + 1, blocking);        if (null == elt) {            return null;        }        sequenceNumber += 1; // next msg sequence number        Message msg = null;        try {            if (LOG.isEnabledFor(Level.DEBUG)) {                LOG.debug("Converting message seqn :"+ (sequenceNumber - 1) +"element to message");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -