public void test_getReuseAddress() throws Exception {
   ServerSocket theSocket = new ServerSocket();
   theSocket.setReuseAddress(true);
   assertTrue("getReuseAddress false when it should be true", theSocket.getReuseAddress());
   theSocket.setReuseAddress(false);
   assertFalse("getReuseAddress true when it should be False", theSocket.getReuseAddress());
 }
Esempio n. 2
0
  void ServerSocketTests() throws Exception {
    ServerSocket s1 = new ServerSocket();

    test("ServerSocket.setReuseAddress(true)");
    s1.setReuseAddress(true);
    check(s1.getReuseAddress());

    test("Socket.setReuseAddress(false)");
    s1.setReuseAddress(false);
    check(!s1.getReuseAddress());

    /* bind to any port */
    s1.bind(new InetSocketAddress(0));

    test("Binding ServerSocket to port already in use should throw " + "a BindException");
    ServerSocket s2 = new ServerSocket();
    try {
      s2.bind(new InetSocketAddress(s1.getLocalPort()));
      failed();
    } catch (BindException e) {
      passed();
    }
    s2.close();

    s1.close();
  }
Esempio n. 3
0
  private static boolean available(int port) {
    if (port <= 0) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
      LogKit.logNothing(e);
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          // should not be thrown, just detect port available.
          LogKit.logNothing(e);
        }
      }
    }
    return false;
  }
  /** {@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;
  }
Esempio n. 5
0
  public static ServerAddress startThreadPoolServer(
      InetSocketAddress address,
      TProcessor processor,
      String serverName,
      String threadName,
      int numThreads)
      throws TTransportException {

    // if port is zero, then we must bind to get the port number
    ServerSocket sock;
    try {
      sock = ServerSocketChannel.open().socket();
      sock.setReuseAddress(true);
      sock.bind(address);
      address = new InetSocketAddress(address.getHostName(), sock.getLocalPort());
    } catch (IOException ex) {
      throw new TTransportException(ex);
    }
    TServerTransport transport = new TBufferedServerSocket(sock, 32 * 1024);
    TThreadPoolServer.Args options = new TThreadPoolServer.Args(transport);
    options.protocolFactory(ThriftUtil.protocolFactory());
    options.transportFactory(ThriftUtil.transportFactory());
    options.processorFactory(new ClientInfoProcessorFactory(processor));
    return new ServerAddress(new TThreadPoolServer(options), address);
  }
    SelectableChannel doConnect() throws IOException, InterruptedException {

      final ServerSocketChannel serverChannel = ServerSocketChannel.open();

      serverChannel.socket().setReceiveBufferSize(BUFFER_SIZE);
      serverChannel.configureBlocking(false);
      final ServerSocket serverSocket = serverChannel.socket();
      serverSocket.setReuseAddress(true);

      serverSocket.bind(details.address());

      // these can be run on this thread
      addPendingRegistration(
          new Runnable() {
            @Override
            public void run() {
              final Attached attached = new Attached();
              attached.connector = ServerConnector.this;
              try {
                serverChannel.register(TcpReplicator.this.selector, OP_ACCEPT, attached);
              } catch (ClosedChannelException e) {
                LOG.error("", e);
              }
            }
          });

      selector.wakeup();

      return serverChannel;
    }
Esempio n. 7
0
  /**
   * Checks to see if a specific port is available.
   *
   * @param port the port to check for availability
   * @return <tt>true</tt> if the port is available, <tt>false</tt> otherwise
   */
  public boolean available(int port) {
    if (port < fromPort || port > toPort) {
      throw new IllegalArgumentException("Port outside port range: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException ignored) {
      /* checkstyle drives me nuts */
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException ignored) {
          /* checkstyle drives me nuts */
        }
      }
    }

    return false;
  }
Esempio n. 8
0
  private LauncherServer() throws IOException {
    this.refCount = new AtomicLong(0);

    ServerSocket server = new ServerSocket();
    try {
      server.setReuseAddress(true);
      server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));

      this.clients = new ArrayList<>();
      this.threadIds = new AtomicLong();
      this.factory = new NamedThreadFactory(THREAD_NAME_FMT);
      this.pending = new ConcurrentHashMap<>();
      this.timeoutTimer = new Timer("LauncherServer-TimeoutTimer", true);
      this.server = server;
      this.running = true;

      this.serverThread =
          factory.newThread(
              new Runnable() {
                @Override
                public void run() {
                  acceptConnections();
                }
              });
      serverThread.start();
    } catch (IOException ioe) {
      close();
      throw ioe;
    } catch (Exception e) {
      close();
      throw new IOException(e);
    }
  }
Esempio n. 9
0
  protected BlockingConnection connect(boolean ultrapeer) throws Exception {
    ServerSocket ss = new ServerSocket();
    ss.setReuseAddress(true);
    ss.bind(new InetSocketAddress(0));
    connectionServices.connectToHostAsynchronously(
        "127.0.0.1", ss.getLocalPort(), ConnectType.PLAIN);
    Socket socket = ss.accept();
    ss.close();

    socket.setSoTimeout(3000);
    InputStream in = socket.getInputStream();
    String word = IOUtils.readWord(in, 9);
    if (!word.equals("GNUTELLA")) throw new IOException("Bad word: " + word);

    HandshakeResponder responder;
    if (ultrapeer) {
      responder = new UltrapeerResponder();
    } else {
      responder = new OldResponder();
    }
    BlockingConnection con = blockingConnectionFactory.createConnection(socket);
    con.initialize(null, responder, 1000);
    replyToPing(con, ultrapeer);
    return con;
  }
Esempio n. 10
0
  private void run() throws IOException {
    ServerSocket serverSocket = new ServerSocket(8888);
    serverSocket.setReuseAddress(true);

    Socket socket = serverSocket.accept();
    new SpdyConnection.Builder(false, socket).handler(this).build();
  }
  public void connectAndFormStreams() throws Exception {

    serverSocket = new ServerSocket();
    serverSocket.setReuseAddress(true);
    serverSocket.bind(new InetSocketAddress(listeningPortNumber));

    while (!Thread.interrupted()) {

      Log.i("Connect", "Before accept()");

      s = serverSocket.accept();

      Log.i("Connect", "after accept");

      is = s.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      br = new BufferedReader(isr);

      Thread serverThread = new Thread(this);
      serverThread.start();
    }

    s.close();
    serverSocket.close();
  }
Esempio n. 12
0
  /**
   * checks if a specific port is available.
   *
   * @param port the port to check for availability
   */
  public static boolean isPortAvailable(int port) {
    if (port < 0 || port > 65535) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
      return false;
    } finally {
      if (ds != null) {
        ds.close();
      }
      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          /* should not be thrown */
        }
      }
    }
  }
Esempio n. 13
0
  /**
   * Checks to see if a specific port is available.
   *
   * @param port the port to check for availability
   */
  private boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          /* should not be thrown */
        }
      }
    }

    return false;
  }
 /**
  * For finding the free port available.
  *
  * @return
  */
 private static int findFreePort() {
   ServerSocket socket = null;
   try {
     socket = new ServerSocket(0);
     socket.setReuseAddress(true);
     int port = socket.getLocalPort();
     try {
       socket.close();
     } catch (IOException e) {
       // Ignore IOException on close()
     }
     return port;
   } catch (Exception e) {
     // Ignore
   } finally {
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
     }
   }
   return 2181;
 }
  private int[] getRandomPorts(int numberOfPorts) {
    IntHashSet ports = new IntHashSet();

    int nextPort = randomIntBetween(49152, 65535);
    for (int i = 0; i < numberOfPorts; i++) {
      boolean foundPortInRange = false;
      while (!foundPortInRange) {
        if (!ports.contains(nextPort)) {
          logger.debug("looking to see if port [{}]is available", nextPort);
          try (ServerSocket serverSocket = new ServerSocket()) {
            // Set SO_REUSEADDR as we may bind here and not be able
            // to reuse the address immediately without it.
            serverSocket.setReuseAddress(NetworkUtils.defaultReuseAddress());
            serverSocket.bind(new InetSocketAddress(nextPort));

            // bind was a success
            logger.debug("port [{}] available.", nextPort);
            foundPortInRange = true;
            ports.add(nextPort);
          } catch (IOException e) {
            // Do nothing
            logger.debug("port [{}] not available.", e, nextPort);
          }
        }
        nextPort = randomIntBetween(49152, 65535);
      }
    }
    return ports.toArray();
  }
Esempio n. 16
0
 private ServerSocket findFreeSocket() {
   ServerSocket socket = null;
   try {
     socket = new ServerSocket(0);
     socket.setReuseAddress(true);
     return socket;
   } catch (IOException e) {
     throw new IllegalStateException("No sockets available for assignment");
   }
 }
Esempio n. 17
0
 private void preSetup() throws SocketException, IOException {
   SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
   serverSocket = serverSocketFactory.createServerSocket(port);
   serverSocket.setReuseAddress(true);
   // if (cipherSuites != null) {
   // ((SSLServerSocket)
   // serverSocket).setEnabledCipherSuites(cipherSuites);
   // }
   LOGGER.debug("|| presetup successful");
 }
Esempio n. 18
0
 public static int getAvailablePort() {
   try {
     ServerSocket s = new ServerSocket(0);
     s.setReuseAddress(true);
     s.close();
     return s.getLocalPort();
   } catch (IOException e) {
     throw new IllegalStateException("Failed to find an available port", e);
   }
 }
Esempio n. 19
0
  public boolean recieveFile(String FilePly) {
    try {
      if (TCPSeverSocket == null) {
        TCPSeverSocket = new ServerSocket();
        TCPSeverSocket.setReuseAddress(true);
        TCPSeverSocket.bind(new InetSocketAddress(DATAPORT));
      }
      while (true) {
        Log.d("recieveFile", "b4 accept");
        Socket sock = TCPSeverSocket.accept();
        Log.d("recieveFile", "data coming");

        ByteBuffer b = ByteBuffer.allocate(4);
        byte[] flarray = b.array();
        InputStream is = sock.getInputStream();
        FileOutputStream fos = new FileOutputStream(FilePly);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int reclen = is.read(flarray, 0, flarray.length);
        ByteBuffer buf = ByteBuffer.wrap(flarray);
        // buf.order(ByteOrder.BIG_ENDIAN);

        int filelen = buf.getInt();

        Log.d("recieveFile", "file len" + Integer.toString(filelen));

        byte[] mybytearray = new byte[filelen];
        int bytesRead = 0;
        while (true) {
          int thisRead = is.read(mybytearray, bytesRead, mybytearray.length - bytesRead);
          bos.write(mybytearray, bytesRead, thisRead);
          bytesRead += thisRead;
          if (bytesRead == mybytearray.length) break;
        }
        bos.flush();

        bos.close();
        sock.close();
        Message dMessage = new Message();
        dMessage.what = 0x4;
        dMessage.obj = "receive file for len" + Integer.toString(bytesRead);

        maininstance.gethandler().sendMessage(dMessage);
        //  File filenew = new File(mFilePly);
        //	int file_size = Integer.parseInt(String.valueOf(filenew.length()));

        // Log.d("recieveFile", "file receive Ok"+Integer.toString(file_size));
        // onPlay(playing);//play that
        Log.d("recieveFile", "file playing OK");
      }

    } catch (Exception ex) {
      Log.e("Socket exception in receive file", ex.toString(), ex);
    }
    return true;
  }
Esempio n. 20
0
  /** {@inheritDoc} */
  @Override
  protected ServerSocketChannel open(SocketAddress localAddress) throws Exception {
    // Creates the listening ServerSocket

    ServerSocketChannel channel = null;

    if (selectorProvider != null) {
      channel = selectorProvider.openServerSocketChannel();
    } else {
      channel = ServerSocketChannel.open();
    }

    boolean success = false;

    try {
      // This is a non blocking socket channel
      channel.configureBlocking(false);

      // Configure the server socket,
      ServerSocket socket = channel.socket();

      // Set the reuseAddress flag accordingly with the setting
      socket.setReuseAddress(isReuseAddress());

      // and bind.
      try {
        socket.bind(localAddress, getBacklog());
      } catch (IOException ioe) {
        // Add some info regarding the address we try to bind to the
        // message
        String newMessage =
            "Error while binding on "
                + localAddress
                + "\n"
                + "original message : "
                + ioe.getMessage();
        Exception e = new IOException(newMessage);
        e.initCause(ioe.getCause());

        // And close the channel
        channel.close();

        throw e;
      }

      // Register the channel within the selector for ACCEPT event
      channel.register(selector, SelectionKey.OP_ACCEPT);
      success = true;
    } finally {
      if (!success) {
        close(channel);
      }
    }
    return channel;
  }
Esempio n. 21
0
 private static Integer findPortNumber(Integer portToTry) {
   try {
     placeHolderSocket = new ServerSocket(portToTry);
     placeHolderSocket.setReuseAddress(true);
     return portToTry;
   } catch (Exception e) {
     portToTry += 10;
     LOGGER.debug("Bad port, trying {}", portToTry);
     return findPortNumber(portToTry);
   }
 }
 public void startServerWorker() throws IOException {
   InetAddress inetAddress = InetAddress.getByName(tcpEventServerConfig.getHostName());
   log.info(
       "EventServer starting event listener on "
           + inetAddress.getHostAddress()
           + ":"
           + tcpEventServerConfig.getPort());
   receiverSocket = new ServerSocket(tcpEventServerConfig.getPort(), 50, inetAddress);
   isRunning = true;
   receiverSocket.setReuseAddress(true);
 }
Esempio n. 23
0
  public netListener(int listenPort, global data) {
    try {
      port = listenPort;
      worldData = data;
      listener = new ServerSocket(listenPort);
      listener.setReuseAddress(true);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 /**
  * Assigns an available port for the test.
  *
  * @param defaultPort If a port cannot be determined, this one is used.
  * @return free port
  */
 @Override
 public int getPort(int defaultPort) {
   try {
     ServerSocket socket = new ServerSocket(0);
     socket.setReuseAddress(true);
     int port = socket.getLocalPort();
     socket.close();
     return port;
   } catch (IOException ioe) {
     return defaultPort;
   }
 }
Esempio n. 25
0
  /**
   * Starts the server, serves all enqueued requests, and shuts the server down.
   *
   * @param port the port to listen to, or 0 for any available port. Automated tests should always
   *     use port 0 to avoid flakiness when a specific port is unavailable.
   */
  public void play(int port) throws IOException {
    if (executor != null) throw new IllegalStateException("play() already called");
    executor = Executors.newCachedThreadPool();
    serverSocket = new ServerSocket(port);
    serverSocket.setReuseAddress(true);

    this.port = serverSocket.getLocalPort();
    executor.execute(
        namedRunnable(
            "MockWebServer-accept-" + port,
            new Runnable() {
              public void run() {
                try {
                  acceptConnections();
                } catch (Throwable e) {
                  logger.log(Level.WARNING, "MockWebServer connection failed", e);
                }

                // This gnarly block of code will release all sockets and all thread,
                // even if any close fails.
                Util.closeQuietly(serverSocket);
                for (Iterator<Socket> s = openClientSockets.keySet().iterator(); s.hasNext(); ) {
                  Util.closeQuietly(s.next());
                  s.remove();
                }
                for (Iterator<SpdyConnection> s = openSpdyConnections.keySet().iterator();
                    s.hasNext(); ) {
                  Util.closeQuietly(s.next());
                  s.remove();
                }
                executor.shutdown();
              }

              private void acceptConnections() throws Exception {
                while (true) {
                  Socket socket;
                  try {
                    socket = serverSocket.accept();
                  } catch (SocketException e) {
                    return;
                  }
                  SocketPolicy socketPolicy = dispatcher.peekSocketPolicy();
                  if (socketPolicy == DISCONNECT_AT_START) {
                    dispatchBookkeepingRequest(0, socket);
                    socket.close();
                  } else {
                    openClientSockets.put(socket, true);
                    serveConnection(socket);
                  }
                }
              }
            }));
  }
Esempio n. 26
0
  public void run() {
    Socket socket = null;
    try {
      serverSocket = new ServerSocket(); // <-- create an unbound socket first
      serverSocket.setReuseAddress(true);
      serverSocket.bind(new InetSocketAddress(ListenerPacket.PORT_PACKET));
      while (true) {
        Log.d(TAG, "Waiting...");
        socket = serverSocket.accept();
        //  long startTime = System.currentTimeMillis();

        // Receive file
        Log.d(TAG, "Receive from " + socket.getInetAddress());

        ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
        byte[] byte_packet = (byte[]) objectInputStream.readObject();
        // long estimatedTime1 = System.currentTimeMillis() - startTime;

        socket.close();
        // long estimatedTime2 = System.currentTimeMillis() - startTime;
        //     System.out.println("Endtime: " + System.nanoTime());

        // if type is IMAGE_TYPE, packet is image.
        byte[] type_packet_byte = new byte[TYPE_LENGTH];
        System.arraycopy(byte_packet, 0, type_packet_byte, 0, TYPE_LENGTH);
        int type_packet = Image.bytesToInt(type_packet_byte);

        switch (type_packet) {
          case IMAGE_TYPE:
            //                        System.out.println("Start time: " + startTime);
            //                        System.out.println("Estimated Time: " + estimatedTime1);
            //                        System.out.println("Estimated Time: " + estimatedTime2);
            saveImage(byte_packet);
            break;
          default:
            break;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
 public ThreadedServer(
     Protocol protocol, SessionManager sessionManager, CommandHandler commandHandler) {
   try {
     this.protocol = protocol;
     this.sessionManager = sessionManager;
     this.commandHandler = commandHandler;
     sSocket = new ServerSocket(PORT);
     sSocket.setReuseAddress(true);
   } catch (IOException e) {
     e.printStackTrace();
     System.exit(0);
   }
 }
Esempio n. 28
0
 public String receiveMessage() {
   try {
     if (receiveSocket.equals(null)) receiveSocket = new ServerSocket(port);
     socket = receiveSocket.accept();
     // start of added code
     receiveSocket.setReuseAddress(true);
     receiveSocket.bind(new InetSocketAddress("localhost", port));
     // End of added code
     BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     return new String(reader.readLine());
   } catch (Exception e) {
     return "";
   }
 }
Esempio n. 29
0
  public Monitor(int port, String key, Server server) throws IOException {
    this.server = server;
    if (port <= 0) {
      throw new IllegalStateException("Bad stop port");
    }
    if (key == null) {
      throw new IllegalStateException("Bad stop key");
    }

    this.key = key;
    setDaemon(true);
    setName("StopJetty9PluginMonitor");
    serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
    serverSocket.setReuseAddress(true);
  }
Esempio n. 30
0
 /**
  * Starts the ConnectionListener. It can be started as often as you want.
  *
  * @throws IOException if the required server socket could not be created.
  * @throws IllegalStateException if ConnectionListener is shutdown.
  */
 public synchronized void start() throws IOException, IllegalStateException {
   logger.info("Start...");
   if (this.shutdown) {
     throw new IllegalStateException("ConnectionListener is shutdown");
   }
   if (!this.running) {
     final ServerSocket ss = new ServerSocket();
     ss.setReuseAddress(true);
     final ConnectionListenerTask task = new ConnectionListenerTask(ss);
     this.executor.execute(task);
     this.currentTask = task;
     this.running = true;
     logger.info("Started.");
   }
 }