Beispiel #1
0
  protected void createWriteBuffer(ByteBuffer buf) {
    if (_primaryWriteBuffer == null) {
      _primaryWriteBuffer = _selectorThread.getPooledBuffer();
      _primaryWriteBuffer.put(buf);
    } else {
      ByteBuffer temp = _selectorThread.getPooledBuffer();
      temp.put(buf);

      int remaining = temp.remaining();
      _primaryWriteBuffer.flip();
      int limit = _primaryWriteBuffer.limit();

      if (remaining >= _primaryWriteBuffer.remaining()) {
        temp.put(_primaryWriteBuffer);
        _selectorThread.recycleBuffer(_primaryWriteBuffer);
        _primaryWriteBuffer = temp;
      } else {
        _primaryWriteBuffer.limit(remaining);
        temp.put(_primaryWriteBuffer);
        _primaryWriteBuffer.limit(limit);
        _primaryWriteBuffer.compact();
        _secondaryWriteBuffer = _primaryWriteBuffer;
        _primaryWriteBuffer = temp;
      }
    }
  }
Beispiel #2
0
 protected void releaseBuffers() {
   if (_primaryWriteBuffer != null) {
     _selectorThread.recycleBuffer(_primaryWriteBuffer);
     _primaryWriteBuffer = null;
     if (_secondaryWriteBuffer != null) {
       _selectorThread.recycleBuffer(_secondaryWriteBuffer);
       _secondaryWriteBuffer = null;
     }
   }
   if (_readBuffer != null) {
     _selectorThread.recycleBuffer(_readBuffer);
     _readBuffer = null;
   }
 }
Beispiel #3
0
  public void testDownload() throws IOException, InstantiationException {
    final SelectorThread st = newThread();
    try {
      st.setAdapter(new StaticResourcesAdapter(tmp.getAbsolutePath()));
      st.listen();
      File file = File.createTempFile("downloaded-largeFile", ".jar", tmp);
      file.deleteOnExit();
      download(String.format("http://localhost:%s/%s", PORT, base.getName()), file);

      Assert.assertEquals("Files should be same size", base.length(), file.length());
    } finally {
      SelectorThreadUtils.stopSelectorThread(st);
    }
  }
Beispiel #4
0
 protected void movePendingWriteBufferTo(ByteBuffer dest) {
   _primaryWriteBuffer.flip();
   dest.put(_primaryWriteBuffer);
   _selectorThread.recycleBuffer(_primaryWriteBuffer);
   _primaryWriteBuffer = _secondaryWriteBuffer;
   _secondaryWriteBuffer = null;
 }
Beispiel #5
0
 public MMOConnection(SelectorThread<T> selectorThread, Socket socket, SelectionKey key) {
   _selectorThread = selectorThread;
   _selectionKey = key;
   _socket = socket;
   _writableByteChannel = socket.getChannel();
   _readableByteChannel = socket.getChannel();
   _sendQueue = new ArrayDeque<SendablePacket<T>>();
   _recvQueue = new MMOExecutableQueue<T>(selectorThread.getExecutor());
 }
 /**
  * Enqueues bytes to the write queue of this handler and notifies the SelectorThread that it wants
  * to write.
  *
  * @param bytes the data to write
  */
 public void write(byte[] bytes) {
   try {
     getWriteQueue().add(ByteBuffer.wrap(bytes));
     SelectorThread.getInstance()
         .interestOps(selectionKey, selectionKey.interestOps() | SelectionKey.OP_WRITE);
   } catch (CancelledKeyException e) {
     close();
   }
 }
Beispiel #7
0
  private SelectorThread newThread() {
    SelectorThread st =
        new SelectorThread() {
          @Override
          public void listen() throws IOException, InstantiationException {
            initEndpoint();
            final CountDownLatch latch = new CountDownLatch(1);
            controller.addStateListener(
                new ControllerStateListenerAdapter() {

                  @Override
                  public void onReady() {
                    enableMonitoring();
                    latch.countDown();
                  }

                  @Override
                  public void onException(Throwable e) {
                    if (latch.getCount() > 0) {
                      logger().log(Level.SEVERE, "Exception during starting the controller", e);
                      latch.countDown();
                    } else {
                      logger().log(Level.SEVERE, "Exception during " + "controller processing", e);
                    }
                  }
                });

            start();

            try {
              latch.await();
            } catch (InterruptedException ex) {
            }

            if (!controller.isStarted()) {
              throw new IllegalStateException("Controller is not started!");
            }
          }
        };
    st.setPort(PORT);
    st.setKeepAliveTimeoutInSeconds(10);

    return st;
  }
  /**
   * Starts a non-blocking connection attempt.
   *
   * @throws IOException
   */
  public void connect() throws IOException {
    sc = SocketChannel.open();
    // Very important. Set to non-blocking. Otherwise a call
    // to connect will block until the connection attempt fails
    // or succeeds.
    sc.configureBlocking(false);
    sc.connect(remoteAddress);

    // Registers itself to receive the connect event.
    selectorThread.registerChannelLater(
        sc,
        SelectionKey.OP_CONNECT,
        this,
        new CallbackErrorHandler() {
          public void handleError(Exception ex) {
            listener.connectionFailed(Connector.this, ex);
          }
        });
  }
  /**
   * Will connect this handler to an address.
   *
   * <p>Use EITHER this method or setSelectionKey, not both.
   *
   * @param a the address to connect to
   */
  @SuppressWarnings("unchecked")
  protected NetworkEventHandler connect(SocketAddress address) throws ConnectException {
    try {
      remoteAddress = address;
      SocketChannel newSocket = SocketChannel.open(address);
      newSocket.socket().setKeepAlive(true);
      newSocket.configureBlocking(false);

      Future<SelectionKey> futureKey = SelectorThread.getInstance().register(newSocket);
      selectionKey = futureKey.get();

      server.getHandlerByAddress().put(address, this);
      selectionKey.attach(this);

      return this;
    } catch (ConnectException e) {
      throw e;
    } catch (ClosedByInterruptException e) {
      throw new ConnectException("" + e);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }