public void test_setReceiveBufferSizeI() throws Exception {
    // now validate case where we try to set to 0
    ServerSocket theSocket = new ServerSocket();
    try {
      theSocket.setReceiveBufferSize(0);
      fail("No exception when receive buffer size set to 0");
    } catch (IllegalArgumentException ex) {
    }
    theSocket.close();

    // now validate case where we try to set to a negative value
    theSocket = new ServerSocket();
    try {
      theSocket.setReceiveBufferSize(-1000);
      fail("No exception when receive buffer size set to -1000");
    } catch (IllegalArgumentException ex) {
    }
    theSocket.close();

    // now just try to set a good value to make sure it is set and there
    // are not exceptions
    theSocket = new ServerSocket();
    theSocket.setReceiveBufferSize(1000);
    theSocket.close();
  }
  /** {@inheritDoc} */
  @Override
  public AsyncServerSocketChannelImpl setOption(SocketOption name, Object value)
      throws IOException {
    if (!(name instanceof StandardSocketOption)) {
      throw new IllegalArgumentException("Unsupported option " + name);
    }

    if (value == null || !name.type().isAssignableFrom(value.getClass())) {
      throw new IllegalArgumentException("Bad parameter for " + name);
    }

    StandardSocketOption stdOpt = (StandardSocketOption) name;
    final ServerSocket socket = channel.socket();

    try {
      switch (stdOpt) {
        case SO_RCVBUF:
          socket.setReceiveBufferSize(((Integer) value).intValue());
          break;

        case SO_REUSEADDR:
          socket.setReuseAddress(((Boolean) value).booleanValue());
          break;

        default:
          throw new IllegalArgumentException("Unsupported option " + name);
      }
    } catch (SocketException e) {
      if (socket.isClosed()) {
        throw Util.initCause(new ClosedChannelException(), e);
      }
      throw e;
    }
    return this;
  }
Пример #3
0
  /**
   * Constructor
   *
   * @param port port to listen on
   * @param myDefaultListener default listener
   * @throws IOException
   */
  public TCPServer(int port, ConnectionEventListener myDefaultListener) throws IOException {
    // Set the current thread's name to owner:tcp server
    super(myDefaultListener.getClass().getSimpleName() + ":" + TCPServer.class.getSimpleName());

    LOGGER.log(Level.INFO, "Creating TCP Server on port {0}", port);
    this.myDefaultListener = myDefaultListener;
    myPort = port;
    myServerSocket = new ServerSocket(myPort);
    myServerSocket.setReceiveBufferSize(BUFFER_SIZE);
    myKeepAliveFlag = true;
  }
Пример #4
0
  void applyServerSocketParams(ServerSocket s, boolean reuseAddress) {

    try {
      s.setReuseAddress(reuseAddress);
    } catch (SocketException e) {
      logger.error("error setting recvBuffer to " + recvBuffer, e);
    }

    if (recvBuffer > 0) {
      try {
        s.setReceiveBufferSize(recvBuffer);
      } catch (SocketException e) {
        logger.error("error setting recvBuffer to " + recvBuffer, e);
      }
    }
  }
Пример #5
0
  /**
   * init the Selector
   *
   * @param ctx
   * @throws java.io.IOException
   */
  private final void initSelector(Context ctx) throws IOException {
    try {
      isShutDown.set(false);

      connectorInstanceHandler =
          new ConnectorInstanceHandler.ConcurrentQueueDelegateCIH(
              getConnectorInstanceHandlerDelegate());

      // Create the socket listener
      selector = Utils.openSelector();

      if (role != Role.CLIENT) {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocket = serverSocketChannel.socket();
        if (receiveBufferSize > 0) {
          try {
            serverSocket.setReceiveBufferSize(receiveBufferSize);
          } catch (SocketException se) {
            if (logger.isLoggable(Level.FINE))
              logger.log(Level.FINE, "setReceiveBufferSize exception ", se);
          } catch (IllegalArgumentException iae) {
            if (logger.isLoggable(Level.FINE))
              logger.log(Level.FINE, "setReceiveBufferSize exception ", iae);
          }
        }

        if (inet == null) {
          portRange.bind(serverSocket, ssBackLog);
        } else {
          portRange.bind(serverSocket, inet, ssBackLog);
        }

        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        serverSocket.setSoTimeout(serverTimeout);

        // Ephemeral support
        port = serverSocket.getLocalPort();
        inet = serverSocket.getInetAddress();
      }
      ctx.getController().notifyReady();
    } catch (SocketException ex) {
      throw new BindException(ex.getMessage() + ": " + port + "=" + this);
    }
  }
Пример #6
0
    @Override
    public final void run() {
      try {
        final TcpPipe enclosing = TcpPipe.this;
        Log.log("startup reciever endpoint for %s", enclosing);

        ServerSocket server = new ServerSocket(0);
        server.setPerformancePreferences(SO_CONNTIME_PREF, SO_LATENCY_PREF, SO_BANDWIDTH_PREF);
        server.setReceiveBufferSize(SO_RCV_BUFF_SIZE);

        int soport = server.getLocalPort();

        Log.log("-- RCV endpoint server socket opened on port %d", soport);

        if (!port_ref.compareAndSet(INIT_PORT, soport))
          throw new IllegalStateException("portUpdater");

        Log.log("-- RCV endpoint port set to %d", port_ref.get());

        Log.log("-- RCV endpoint now accepting connection ..");
        latch.countDown();
        Socket socket = server.accept();
        socket.setKeepAlive(true);
        socket.setPerformancePreferences(SO_CONNTIME_PREF, SO_LATENCY_PREF, SO_BANDWIDTH_PREF);
        socket.setTcpNoDelay(true);
        socket.setSendBufferSize(SO_RCV_BUFF_SIZE);
        SocketAddress remsoaddr = socket.getRemoteSocketAddress();

        Log.log("-- RCV endpoint accepted connection from %s", remsoaddr);

        if (!rcvsocket_ref.compareAndSet(null, socket))
          throw new IllegalStateException("recvInUpdater");

      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        Log.log("server endpoint established");
      }
    }
Пример #7
0
  private static void initSocket(ServerSocket socket, Configuration conf) throws SocketException {
    final int[] performancePreferences = conf.performancePreferences();
    if (performancePreferences != null) {
      int n = performancePreferences.length;
      int connectionTime = 0;
      int latency = 0;
      int bandWidth = 0;
      if (n > 2) {
        connectionTime = performancePreferences[0];
        latency = performancePreferences[1];
        bandWidth = performancePreferences[2];
      } else if (n > 1) {
        connectionTime = performancePreferences[0];
        latency = performancePreferences[1];
      } else if (n > 0) connectionTime = performancePreferences[0];

      socket.setPerformancePreferences(connectionTime, latency, bandWidth);
    }

    if (conf.reuseAddr()) socket.setReuseAddress(true);

    final Integer recvBufSize = conf.recvBufSize();
    if (recvBufSize != null) socket.setReceiveBufferSize(recvBufSize);
  }
Пример #8
0
  // Runnable IMPLEMENTATION /////////////////////////////////////////////////
  public void run() {
    synchronized (this) {
      if (selectorthread != null)
        throw new IllegalStateException(getClass().getName() + " can only be started once.");
      selectorthread = Thread.currentThread();
      if (isclosed.get()) {
        return;
      }
    }
    selectorthread.setName("WebsocketSelector" + selectorthread.getId());
    try {
      server = ServerSocketChannel.open();
      server.configureBlocking(false);
      ServerSocket socket = server.socket();
      socket.setReceiveBufferSize(WebSocket.RCVBUF);
      socket.bind(address);
      selector = Selector.open();
      server.register(selector, server.validOps());
    } catch (IOException ex) {
      handleFatal(null, ex);
      return;
    }
    try {
      while (!selectorthread.isInterrupted()) {
        SelectionKey key = null;
        WebSocketImpl conn = null;
        try {
          selector.select();
          registerWrite();

          Set<SelectionKey> keys = selector.selectedKeys();
          Iterator<SelectionKey> i = keys.iterator();

          while (i.hasNext()) {
            key = i.next();

            if (!key.isValid()) {
              // Object o = key.attachment();
              continue;
            }

            if (key.isAcceptable()) {
              if (!onConnect(key)) {
                key.cancel();
                continue;
              }

              SocketChannel channel = server.accept();
              channel.configureBlocking(false);
              WebSocketImpl w = wsf.createWebSocket(this, drafts, channel.socket());
              w.key = channel.register(selector, SelectionKey.OP_READ, w);
              w.channel = wsf.wrapChannel(channel, w.key);
              i.remove();
              allocateBuffers(w);
              continue;
            }

            if (key.isReadable()) {
              conn = (WebSocketImpl) key.attachment();
              ByteBuffer buf = takeBuffer();
              try {
                if (SocketChannelIOHelper.read(buf, conn, (ByteChannel) conn.channel)) {
                  conn.inQueue.put(buf);
                  queue(conn);
                  i.remove();
                  if (conn.channel instanceof WrappedByteChannel) {
                    if (((WrappedByteChannel) conn.channel).isNeedRead()) {
                      iqueue.add(conn);
                    }
                  }
                } else {
                  pushBuffer(buf);
                }
              } catch (IOException e) {
                pushBuffer(buf);
                throw e;
              } catch (RuntimeException e) {
                pushBuffer(buf);
                throw e;
              }
            }
            if (key.isWritable()) {
              conn = (WebSocketImpl) key.attachment();
              if (SocketChannelIOHelper.batch(conn, (ByteChannel) conn.channel)) {
                if (key.isValid()) key.interestOps(SelectionKey.OP_READ);
              }
            }
          }
          while (!iqueue.isEmpty()) {
            conn = iqueue.remove(0);
            WrappedByteChannel c = ((WrappedByteChannel) conn.channel);
            ByteBuffer buf = takeBuffer();
            try {
              if (SocketChannelIOHelper.readMore(buf, conn, c)) iqueue.add(conn);
              conn.inQueue.put(buf);
              queue(conn);
            } finally {
              pushBuffer(buf);
            }
          }
        } catch (CancelledKeyException e) {
          // an other thread may cancel the key
        } catch (IOException ex) {
          if (key != null) key.cancel();
          handleIOException(conn, ex);
        } catch (InterruptedException e) {
          return; // FIXME controlled shutdown
        }
      }

    } catch (RuntimeException e) {
      // should hopefully never occur
      handleFatal(null, e);
    }
  }
 public void setReceiveBufferSize(int size) throws SocketException {
   serverSocket.setReceiveBufferSize(size);
 }
Пример #10
0
  // Runnable IMPLEMENTATION /////////////////////////////////////////////////
  public void run() {
    if (selectorthread != null)
      throw new IllegalStateException(
          "This instance of "
              + getClass().getSimpleName()
              + " can only be started once the same time.");
    selectorthread = Thread.currentThread();
    selectorthread.setName("WebsocketSelector" + selectorthread.getId());
    try {
      server = ServerSocketChannel.open();
      server.configureBlocking(false);
      ServerSocket socket = server.socket();
      socket.setReceiveBufferSize(WebSocket.RCVBUF);
      socket.bind(address);
      selector = Selector.open();
      server.register(selector, server.validOps());
    } catch (IOException ex) {
      onWebsocketError(null, ex);
      return;
    }
    try {
      while (!selectorthread.isInterrupted()) {
        SelectionKey key = null;
        WebSocketImpl conn = null;
        try {
          selector.select();
          registerWrite();

          Set<SelectionKey> keys = selector.selectedKeys();
          Iterator<SelectionKey> i = keys.iterator();

          while (i.hasNext()) {
            key = i.next();

            if (!key.isValid()) {
              // Object o = key.attachment();
              continue;
            }

            if (key.isAcceptable()) {
              SocketChannel channel = server.accept();
              channel.configureBlocking(false);
              WebSocketImpl c = wsf.createWebSocket(this, drafts, channel.socket());
              c.key = channel.register(selector, SelectionKey.OP_READ, c);
              c.ioobject = wsf.wrapChannel(channel);
              i.remove();
              allocateBuffers(c);
              continue;
            }

            if (key.isReadable()) {
              conn = (WebSocketImpl) key.attachment();
              ByteBuffer buf = takeBuffer();
              try {
                if (SocketChannelIOHelper.read(buf, conn, (ByteChannel) conn.ioobject)) {
                  conn.in.put(buf);
                  queue(conn);
                  i.remove();
                } else {
                  pushBuffer(buf);
                }
              } catch (IOException e) {
                pushBuffer(buf);
                throw e;
              } catch (RuntimeException e) {
                pushBuffer(buf);
                throw e;
              }
            }
            if (key.isWritable()) {
              conn = (WebSocketImpl) key.attachment();
              if (SocketChannelIOHelper.batch(conn, (ByteChannel) conn.ioobject)) {
                if (key.isValid())
                  key.channel().register(selector, SelectionKey.OP_READ, key.attachment());
              }
            }
          }
        } catch (CancelledKeyException e) {
          // an other thread may cancel the key
        } catch (IOException ex) {
          if (key != null) key.cancel();
          handleIOException(conn, ex);
        } catch (InterruptedException e) {
          return;
        }
      }
    } catch (RuntimeException e) {
      // should hopefully never occur
      handleFatal(null, e);
    }
  }
Пример #11
0
 @Signature(@Arg("size"))
 public Memory setReceiveBufferSize(Environment env, Memory... args) throws SocketException {
   socket.setReceiveBufferSize(args[0].toInteger());
   return Memory.NULL;
 }