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

📄 directappsocket.java

📁 pastry的java实现的2.0b版
💻 JAVA
字号:
/*************************************************************************"FreePastry" Peer-to-Peer Application Development Substrate Copyright 2002, Rice University. All rights reserved.Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:- Redistributions of source code must retain the above copyrightnotice, this list of conditions and the following disclaimer.- Redistributions in binary form must reproduce the above copyrightnotice, this list of conditions and the following disclaimer in thedocumentation and/or other materials provided with the distribution.- Neither  the name  of Rice  University (RICE) nor  the names  of itscontributors may be  used to endorse or promote  products derived fromthis software without specific prior written permission.This software is provided by RICE and the contributors on an "as is"basis, without any representations or warranties of any kind, expressor implied including, but not limited to, representations orwarranties of non-infringement, merchantability or fitness for aparticular purpose. In no event shall RICE or contributors be liablefor any direct, indirect, incidental, special, exemplary, orconsequential damages (including, but not limited to, procurement ofsubstitute goods or services; loss of use, data, or profits; orbusiness interruption) however caused and on any theory of liability,whether in contract, strict liability, or tort (including negligenceor otherwise) arising in any way out of the use of this software, evenif advised of the possibility of such damage.********************************************************************************//* *  Created on Jan 30, 2006 */package rice.pastry.direct;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.ClosedChannelException;import java.util.*;import rice.p2p.commonapi.*;import rice.p2p.commonapi.appsocket.*;import rice.p2p.commonapi.exception.*;import rice.pastry.client.PastryAppl;/** * DESCRIBE THE CLASS * * @version $Id: pretty.settings 2305 2005-03-11 20:22:33Z jeffh $ * @author jeffh */public class DirectAppSocket {  DirectNodeHandle acceptorNodeHandle;  PastryAppl acceptorAppl;  AppSocketReceiver connectorReceiver;  PastryAppl connectorAppl;  NetworkSimulator simulator;  DirectAppSocketEndpoint acceptorEndpoint;  DirectAppSocketEndpoint connectorEndpoint;  /**   * DESCRIBE THE FIELD   */  public final static byte[] EOF = new byte[0];  /**   * The sum the simulated read/write buffers for one direction of a socket   */  private final static int MAX_BYTES_IN_FLIGHT = 10000;  /**   * Constructor for DirectAppSocket.   *   * @param acceptor DESCRIBE THE PARAMETER   * @param connector DESCRIBE THE PARAMETER   * @param connectorAppl DESCRIBE THE PARAMETER   * @param simulator DESCRIBE THE PARAMETER   */  DirectAppSocket(DirectNodeHandle acceptor, AppSocketReceiver connector, PastryAppl connectorAppl, NetworkSimulator simulator) {    this.acceptorNodeHandle = acceptor;    DirectPastryNode acceptorNode = acceptor.getRemote();    this.connectorReceiver = connector;    this.connectorAppl = connectorAppl;    this.simulator = simulator;    acceptorAppl = acceptorNode.getMessageDispatch().getDestinationByAddress(connectorAppl.getAddress());    acceptorEndpoint = new DirectAppSocketEndpoint(acceptor);    connectorEndpoint = new DirectAppSocketEndpoint(connectorAppl.getNodeHandle());    acceptorEndpoint.setCounterpart(connectorEndpoint);    connectorEndpoint.setCounterpart(acceptorEndpoint);  }  /**   * Gets the AcceptorDelivery attribute of the DirectAppSocket object   *   * @return The AcceptorDelivery value   */  public Delivery getAcceptorDelivery() {    return new AcceptorDelivery();  }  /**   * DESCRIBE THE CLASS   *   * @version $Id: pretty.settings 2305 2005-03-11 20:22:33Z jeffh $   * @author jeffh   */  class DirectAppSocketEndpoint implements AppSocket {    DirectAppSocketEndpoint counterpart;    AppSocketReceiver reader;    AppSocketReceiver writer;    NodeHandle localNodeHandle;    boolean inputClosed;    boolean outputClosed;    // these three are tightly related, and should only be modified in synchronized methods on DirectAppSocketEndpoint.this    // bytes that are either in deliveries, or in the local buffer    int bytesInFlight = 0;    /**     * of byte[]     */    LinkedList byteDeliveries = new LinkedList();    /**     * The offset of the first delivery, in case the reader didn't have enough     * space to read everything available.     */    int firstOffset = 0;    /**     * Constructor for DirectAppSocketEndpoint.     *     * @param localNodeHandle DESCRIBE THE PARAMETER     */    public DirectAppSocketEndpoint(NodeHandle localNodeHandle) {      this.localNodeHandle = localNodeHandle;    }    /**     * Gets the RemoteNodeHandle attribute of the DirectAppSocketEndpoint object     *     * @return The RemoteNodeHandle value     */    public NodeHandle getRemoteNodeHandle() {      return counterpart.localNodeHandle;    }    /**     * Sets the Counterpart attribute of the DirectAppSocketEndpoint object     *     * @param counterpart The new Counterpart value     */    public void setCounterpart(DirectAppSocketEndpoint counterpart) {      this.counterpart = counterpart;    }    /**     * DESCRIBE THE METHOD     *     * @param dsts DESCRIBE THE PARAMETER     * @param offset DESCRIBE THE PARAMETER     * @param length DESCRIBE THE PARAMETER     * @return DESCRIBE THE RETURN VALUE     */    public long read(ByteBuffer[] dsts, int offset, int length) {      int lengthRead = 0;      synchronized (this) {        if (byteDeliveries.getFirst() == EOF) {          inputClosed = true;          return -1;        }        Iterator i = byteDeliveries.iterator();        // loop over all messages to be delivered        while (i.hasNext()) {          byte[] msg = (byte[]) i.next();          // loop through all the dsts, and fill them with the current message if possible          for (int dstCtr = offset; dstCtr < offset + length; dstCtr++) {            ByteBuffer curBuffer = dsts[dstCtr];            int lengthToPut = curBuffer.remaining();            if (lengthToPut > (msg.length - firstOffset)) {              lengthToPut = msg.length - firstOffset;            }            curBuffer.put(msg, firstOffset, lengthToPut);            firstOffset += lengthToPut;            lengthRead += lengthToPut;            // we finished a message            if (firstOffset == msg.length) {              break;            }            // for distCtr loop            // optimization: if we are here then there must be no more remaining in curBuffer            offset = dstCtr + 1;          }          // see if we finished a message          if (firstOffset == msg.length) {            i.remove();            firstOffset = 0;          } else {            break;            // i.hasNext() loop          }        }      }      // synchronized(this)      bytesInFlight -= lengthRead;      simulator.enqueueDelivery(        new Delivery() {          public void deliver() {            notifyCanWrite();          }        });      return lengthRead;    }    /**     * DESCRIBE THE METHOD     *     * @param srcs DESCRIBE THE PARAMETER     * @param offset DESCRIBE THE PARAMETER     * @param length DESCRIBE THE PARAMETER     * @return DESCRIBE THE RETURN VALUE     * @exception IOException DESCRIBE THE EXCEPTION     */    public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {      if (outputClosed) {        throw new ClosedChannelException();      }      int availableToWrite = 0;      for (int i = offset; i < offset + length; i++) {        availableToWrite += srcs[i].remaining();      }      int lengthToWrite;      synchronized (counterpart) {        lengthToWrite = MAX_BYTES_IN_FLIGHT - counterpart.bytesInFlight;        if (lengthToWrite > availableToWrite) {          lengthToWrite = availableToWrite;        }        counterpart.bytesInFlight += lengthToWrite;      }      final byte[] msg = new byte[lengthToWrite];      int remaining = lengthToWrite;      int i = offset;      while (remaining > 0) {        int lengthToReadFromBuffer = srcs[i].remaining();        if (remaining < lengthToReadFromBuffer) {          lengthToReadFromBuffer = remaining;        }        srcs[i].get(msg, lengthToWrite - remaining, lengthToReadFromBuffer);        remaining -= lengthToReadFromBuffer;        i++;      }      simulator.enqueueDelivery(        new Delivery() {          public void deliver() {            counterpart.addToReadQueue(msg);          }        });      return lengthToWrite;    }    /**     * only called on simulator thread     *     * @param msg The feature to be added to the ToReadQueue attribute     */    protected void addToReadQueue(byte[] msg) {      synchronized (this) {        byteDeliveries.addLast(msg);      }      notifyCanRead();    }    /**     * must be called on the simulator thread     */    protected void notifyCanWrite() {      if (writer == null) {        return;      }      if (counterpart.bytesInFlight < MAX_BYTES_IN_FLIGHT) {        AppSocketReceiver temp = writer;        writer = null;        temp.receiveSelectResult(this, false, true);      }    }    /**     * must be called on the simulator thread     */    protected void notifyCanRead() {      if (byteDeliveries.isEmpty()) {        return;      }      if (reader != null) {        AppSocketReceiver temp = reader;        reader = null;        temp.receiveSelectResult(this, true, false);      }    }    /**     * Can be called on any thread     *     * @param wantToRead DESCRIBE THE PARAMETER     * @param wantToWrite DESCRIBE THE PARAMETER     * @param timeout DESCRIBE THE PARAMETER     * @param receiver DESCRIBE THE PARAMETER     */    public void register(boolean wantToRead, boolean wantToWrite, int timeout,                         AppSocketReceiver receiver) {      if (wantToWrite) {        writer = receiver;        simulator.enqueueDelivery(          new Delivery() {            public void deliver() {              notifyCanWrite();              // only actually notifies if proper at the time            }          });      }      if (wantToRead) {        reader = receiver;        simulator.enqueueDelivery(          new Delivery() {            public void deliver() {              notifyCanRead();              // only actually notifies if proper at the time            }          });      }    }    /**     * DESCRIBE THE METHOD     */    public void shutdownOutput() {      outputClosed = true;      simulator.enqueueDelivery(        new Delivery() {          public void deliver() {            counterpart.addToReadQueue(EOF);          }        });    }    /**     * DESCRIBE THE METHOD     */    public void shutdownInput() {      inputClosed = true;    }    /**     * DESCRIBE THE METHOD     */    public void close() {      shutdownOutput();      shutdownInput();    }  }  /**   * DESCRIBE THE CLASS   *   * @version $Id: pretty.settings 2305 2005-03-11 20:22:33Z jeffh $   * @author jeffh   */  class AcceptorDelivery implements Delivery {    /**     * DESCRIBE THE METHOD     */    public void deliver() {      if (acceptorNodeHandle.isAlive()) {        if (acceptorAppl == null) {          simulator.enqueueDelivery(new ConnectorExceptionDelivery(new AppNotRegisteredException()));        } else {          if (acceptorAppl.receiveSocket(acceptorEndpoint)) {            simulator.enqueueDelivery(new ConnectorDelivery());          } else {            simulator.enqueueDelivery(new ConnectorExceptionDelivery(new NoReceiverAvailableException()));          }        }      } else {        simulator.enqueueDelivery(new ConnectorExceptionDelivery(new NodeIsDeadException()));      }    }  }  /**   * DESCRIBE THE CLASS   *   * @version $Id: pretty.settings 2305 2005-03-11 20:22:33Z jeffh $   * @author jeffh   */  class ConnectorDelivery implements Delivery {    /**     * DESCRIBE THE METHOD     */    public void deliver() {      if (connectorAppl.getNodeHandle().isAlive()) {        connectorReceiver.receiveSocket(connectorEndpoint);      } else {        System.out.println("NOT IMPLEMENTED: Connector died during application socket initiation.");//        simulator.enqueueDelivery(new ConnectorExceptionDelivery(new NodeIsDeadException(acceptorNodeHandle)));      }    }  }  /**   * DESCRIBE THE CLASS   *   * @version $Id: pretty.settings 2305 2005-03-11 20:22:33Z jeffh $   * @author jeffh   */  class ConnectorExceptionDelivery implements Delivery {    Exception e;    /**     * Constructor for ConnectorExceptionDelivery.     *     * @param e DESCRIBE THE PARAMETER     */    public ConnectorExceptionDelivery(Exception e) {      this.e = e;    }    /**     * DESCRIBE THE METHOD     */    public void deliver() {      connectorReceiver.receiveException(null, e);    }  }}

⌨️ 快捷键说明

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