private void startServers(int proxyPort, int destPort) {
    try {
      _proxyServer = new ServerSocket();
      _proxyServer.bind(new InetSocketAddress(proxyPort));
      _destinationServer = new ServerSocket();
      _destinationServer.bind(new InetSocketAddress(destPort));
    } catch (IOException iox) {
      ErrorService.error(iox);
    }

    Thread proxyThread =
        new ManagedThread() {
          public void managedRun() {
            proxyLoop();
          }
        };
    proxyThread.setDaemon(true);
    proxyThread.start();

    Thread destThread =
        new ManagedThread() {
          public void managedRun() {
            destLoop();
          }
        };
    destThread.setDaemon(true);
    destThread.start();
  }
Ejemplo 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();
  }
Ejemplo n.º 3
0
  @Override
  protected void startInternal() throws Exception {
    c_logger.info(StrUtil.join("Starting ", this, "..."));

    m_stopped = false;

    final Configuration conf = m_conf;
    InetAddress bindAddr = null;
    final String host = conf.bindAddr();
    if (host != null) bindAddr = InetAddress.getByName(host);

    final ServerSocketChannel ssc = ServerSocketChannel.open();
    try {
      final ServerSocket socket = ssc.socket();
      initSocket(socket, conf);
      final SocketAddress ep = new InetSocketAddress(bindAddr, conf.port());
      final Integer backlog = conf.backlog();
      if (backlog == null) socket.bind(ep);
      else socket.bind(ep, backlog);

      m_ssc = ssc;

      m_acceptor.doAccept(this);

      c_logger.info(StrUtil.join(this, " started, listening on ", socket.getLocalSocketAddress()));
    } catch (Exception e) {
      try {
        ssc.close();
      } catch (Throwable t) {
      }
      c_logger.error(StrUtil.join(this, " failed to start"), e);
      m_ssc = null;
      throw e;
    }
  }
Ejemplo n.º 4
0
 public SocksServer(int port) throws IOException {
   this.port = port;
   server = new ServerSocket();
   if (port == 0) {
     server.bind(null);
     this.port = server.getLocalPort();
   } else {
     server.bind(new InetSocketAddress(port));
   }
 }
Ejemplo n.º 5
0
  public static void main(String[] args) {
    ServerSocket serverSocket = null;

    try {
      // 1. 서버소켓 생성
      serverSocket = new ServerSocket();

      // 2. binding
      InetAddress inetAddress = InetAddress.getLocalHost();
      String hostAddress = inetAddress.getHostAddress();
      serverSocket.bind(new InetSocketAddress(hostAddress, PORT));
      log("연결 기다림 " + hostAddress + ":" + PORT);

      // 3. 연결 요청 기다림
      while (true) {
        Socket socket = serverSocket.accept();

        Thread thread = new HttpThread(socket);
        thread.start();
      }
    } catch (IOException ex) {
      log("error:" + ex);
    } finally {
      if (serverSocket != null && serverSocket.isClosed() == false) {
        try {
          serverSocket.close();
        } catch (IOException ex) {
          log("error:" + ex);
        }
      }
    }
  }
Ejemplo n.º 6
0
  /**
   * Start the server.
   *
   * @throws IOException if the socket is in use.
   */
  public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind(
        (hostname != null)
            ? new InetSocketAddress(hostname, myPort)
            : new InetSocketAddress(myPort));

    myThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                do {
                  try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(
                        new Runnable() {
                          @Override
                          public void run() {
                            OutputStream outputStream = null;
                            try {
                              outputStream = finalAccept.getOutputStream();
                              TempFileManager tempFileManager = tempFileManagerFactory.create();
                              HTTPSession session =
                                  new HTTPSession(
                                      tempFileManager,
                                      inputStream,
                                      outputStream,
                                      finalAccept.getInetAddress());
                              while (!finalAccept.isClosed()) {
                                session.execute();
                              }
                            } catch (Exception e) {
                              // When the socket is closed by the client,
                              // we throw our own SocketException
                              // to break the "keep alive" loop above.
                              if (!(e instanceof SocketException
                                  && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                e.printStackTrace();
                              }
                            } finally {
                              safeClose(outputStream);
                              safeClose(inputStream);
                              safeClose(finalAccept);
                              unRegisterConnection(finalAccept);
                            }
                          }
                        });
                  } catch (IOException e) {
                  }
                } while (!myServerSocket.isClosed());
              }
            });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
  }
Ejemplo n.º 7
0
        @Override
        public void validateValue(String hostAndPort) throws IllegalArgumentException {

          if ((hostAndPort == null) || (hostAndPort.length() == 0)) {
            throw new IllegalArgumentException("The value cannot be null or zero length: " + name);
          }
          int colonToken = hostAndPort.indexOf(":");
          String hostName = (colonToken >= 0) ? hostAndPort.substring(0, colonToken) : hostAndPort;
          ServerSocket testSocket = null;
          try {
            testSocket = new ServerSocket();
            /* The bind will fail if the hostName does not name this m/c.*/
            testSocket.bind(new InetSocketAddress(hostName, 0));
            testSocket.close();
          } catch (UnknownHostException e) {
            throw new IllegalArgumentException(
                "Property: " + name + "Invalid hostname: " + e.getMessage());
          } catch (IOException e) {

            /*
             * Server socket could not be bound to any port. Hostname is
             * not associated with this m/c.
             */
            throw new IllegalArgumentException(
                "Invalid hostname: "
                    + hostName
                    + " The host name is not associated with this machine.");
          }

          if (colonToken >= 0) {
            validatePort(hostAndPort.substring(colonToken + 1));
          }
        }
  /** @tests java.net.ServerSocket#getLocalSocketAddress() */
  public void test_getLocalSocketAddress() throws Exception {
    // set up server connect and then validate that we get the right
    // response for the local address
    ServerSocket theSocket = new ServerSocket(0, 5, InetAddress.getLocalHost());
    int portNumber = theSocket.getLocalPort();
    assertTrue(
        "Returned incorrect InetSocketAddress(1):"
            + theSocket.getLocalSocketAddress().toString()
            + "Expected: "
            + (new InetSocketAddress(InetAddress.getLocalHost(), portNumber)).toString(),
        theSocket
            .getLocalSocketAddress()
            .equals(new InetSocketAddress(InetAddress.getLocalHost(), portNumber)));
    theSocket.close();

    // now create a socket that is not bound and validate we get the
    // right answer
    theSocket = new ServerSocket();
    assertNull(
        "Returned incorrect InetSocketAddress -unbound socket- Expected null",
        theSocket.getLocalSocketAddress());

    // now bind the socket and make sure we get the right answer
    theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
    int localPort = theSocket.getLocalPort();
    assertEquals(
        "Returned incorrect InetSocketAddress(2):",
        theSocket.getLocalSocketAddress(),
        new InetSocketAddress(InetAddress.getLocalHost(), localPort));
    theSocket.close();
  }
Ejemplo n.º 9
0
  @Test
  public void testBind() throws Exception {
    Configuration conf = new Configuration();
    ServerSocket socket = new ServerSocket();
    InetSocketAddress address = new InetSocketAddress("0.0.0.0", 0);
    socket.bind(address);
    try {
      int min = socket.getLocalPort();
      int max = min + 100;
      conf.set("TestRange", min + "-" + max);

      ServerSocket socket2 = new ServerSocket();
      InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
      Server.bind(socket2, address2, 10, conf, "TestRange");
      try {
        assertTrue(socket2.isBound());
        assertTrue(socket2.getLocalPort() > min);
        assertTrue(socket2.getLocalPort() <= max);
      } finally {
        socket2.close();
      }
    } finally {
      socket.close();
    }
  }
Ejemplo n.º 10
0
  private Server createServer(final DummyServlet servlet) throws Exception {
    int port;
    try (ServerSocket socket = new ServerSocket()) {
      socket.bind(new InetSocketAddress(0));
      port = socket.getLocalPort();
    }
    baseUri = new URI("http", null, "127.0.0.1", port, null, null, null);

    HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setSendServerVersion(false);
    httpConfiguration.setSendXPoweredBy(false);

    server = new Server();

    ServerConnector httpConnector =
        new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));
    httpConnector.setPort(port);
    httpConnector.setName("http");
    server.addConnector(httpConnector);

    ServletHolder servletHolder = new ServletHolder(servlet);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.addServlet(servletHolder, "/*");
    HandlerCollection handlers = new HandlerCollection();
    handlers.addHandler(context);
    server.setHandler(handlers);
    return server;
  }
Ejemplo n.º 11
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);
  }
Ejemplo n.º 12
0
    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;
    }
Ejemplo n.º 13
0
 /*
  * Receives votes from clients, passes them on to Voting
  * Notice that this has to happen over TCP instead of UDP to make voting reliable
  */
 public void run() {
   try {
     ServerSocket serverSocket = new ServerSocket();
     InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), VOTING_PORT);
     serverSocket.bind(address);
     serverSocket.setSoTimeout(200);
     while (!Thread.currentThread().isInterrupted()) {
       // TODO: May need to thread this further if client submissions get larger
       try {
         Socket socket = serverSocket.accept();
         BufferedReader reader =
             new BufferedReader(new InputStreamReader(socket.getInputStream()));
         String s = null;
         while ((s = reader.readLine()) != null) {
           voting.addVote(s);
           logger.log(Level.FINE, "Received vote for " + s);
         }
       } catch (SocketTimeoutException e) {
         logger.log(Level.FINE, "No votes received in 200ms interval");
       }
     }
   } catch (IOException ex) {
     logger.log(Level.SEVERE, null, ex);
   }
 }
Ejemplo n.º 14
0
 public void serve(int port) throws IOException {
   ServerSocketChannel serverChannel = ServerSocketChannel.open();
   serverChannel.configureBlocking(false);
   ServerSocket ss = serverChannel.socket();
   InetSocketAddress address = new InetSocketAddress(port);
   // Binds the server to the selected port
   ss.bind(address);
   // Opens the Selector for handling channels
   Selector selector = Selector.open();
   // Registers the ServerSocket with the Selector to accept connections
   serverChannel.register(selector, SelectionKey.OP_ACCEPT);
   final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes());
   while (true) {
     try {
       // Waits for new events to process; blocks until the next incoming event
       selector.select();
     } catch (IOException e) {
       e.printStackTrace();
       break;
     }
     // Obtains all SelectionKey instances that received events
     Set<SelectionKey> readyKeys = selector.selectedKeys();
     Iterator<SelectionKey> iterator = readyKeys.iterator();
     while (iterator.hasNext()) {
       SelectionKey key = iterator.next();
       iterator.remove();
       try {
         // Checks if the event is a new connection ready to be accepted
         if (key.isAcceptable()) {
           ServerSocketChannel server = (ServerSocketChannel) key.channel();
           SocketChannel client = server.accept();
           client.configureBlocking(false);
           // Accepts client and registers it with the selector
           client.register(
               selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, msg.duplicate());
           System.out.println("Accepted connection from " + client);
         }
         // Checks if the socket is ready for writing data
         if (key.isWritable()) {
           SocketChannel client = (SocketChannel) key.channel();
           ByteBuffer buffer = (ByteBuffer) key.attachment();
           while (buffer.hasRemaining()) {
             // Writes data to the connected client
             if (client.write(buffer) == 0) {
               break;
             }
           }
           // Closes the connection
           client.close();
         }
       } catch (IOException e) {
         key.cancel();
         try {
           key.channel().close();
         } catch (IOException e1) {
         }
       }
     }
   }
 }
Ejemplo n.º 15
0
  private void runServer() {
    String logFile = properties.getProperty("logFile");
    Utils.setLogFile(logFile, Server.class.getName());
    int port = Integer.parseInt(properties.getProperty("port"));
    String ip = properties.getProperty("serverIp");

    Logger.getLogger(Server.class.getName())
        .log(Level.INFO, "Server started. Listening on: " + port + ", bound to: " + ip);
    try {
      serverSocket = new ServerSocket();
      serverSocket.bind(new InetSocketAddress(ip, port));
      do {
        Socket socket = serverSocket.accept(); // Important Blocking call
        Logger.getLogger(Server.class.getName()).log(Level.INFO, "Connected to a client");

        ClientHandler tmpClient = new ClientHandler(socket, this);
        clients.add(tmpClient);
        tmpClient.start();

      } while (keepRunning);
    } catch (IOException ex) {
      Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      Utils.closeLogger(Server.class.getName());
    }
  }
  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();
  }
Ejemplo n.º 17
0
  @Test
  public void testBindError() throws Exception {
    Configuration conf = new Configuration();
    ServerSocket socket = new ServerSocket();
    InetSocketAddress address = new InetSocketAddress("0.0.0.0", 0);
    socket.bind(address);
    try {
      int min = socket.getLocalPort();
      conf.set("TestRange", min + "-" + min);

      ServerSocket socket2 = new ServerSocket();
      InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
      boolean caught = false;
      try {
        Server.bind(socket2, address2, 10, conf, "TestRange");
      } catch (BindException e) {
        caught = true;
      } finally {
        socket2.close();
      }
      assertTrue("Failed to catch the expected bind exception", caught);
    } finally {
      socket.close();
    }
  }
  /** {@inheritDoc} */
  @Override
  public AsyncServerSocketChannelImpl bind(SocketAddress local, int backlog) throws IOException {
    if ((local != null) && (!(local instanceof InetSocketAddress))) {
      throw new UnsupportedAddressTypeException();
    }

    InetSocketAddress inetLocal = (InetSocketAddress) local;
    if ((inetLocal != null) && inetLocal.isUnresolved()) {
      throw new UnresolvedAddressException();
    }

    final ServerSocket socket = channel.socket();

    try {
      socket.bind(local, backlog);
    } catch (SocketException e) {
      if (socket.isBound()) {
        throw Util.initCause(new AlreadyBoundException(), e);
      }
      if (socket.isClosed()) {
        throw Util.initCause(new ClosedChannelException(), e);
      }
      throw e;
    }
    return this;
  }
Ejemplo n.º 19
0
 public void start() throws IOException {
   ss = new ServerSocket();
   ss.bind(proxyAddress);
   System.out.println("Starting proxy");
   es.submit(
       new Runnable() {
         public void run() {
           for (; ; ) {
             try {
               pause.await();
               final Socket in = ss.accept();
               pause.await();
               Socket out = new Socket();
               out.connect(remoteAddress);
               Connection con = new Connection(in, out);
               con.inToOut.start();
               con.outToIn.start();
               connections.add(con);
             } catch (Throwable t) {
               return;
             }
           }
         }
       });
 }
Ejemplo n.º 20
0
 public static void main(String[] args) throws IOException {
   String ip = "localhost";
   int port = 4321;
   if (args.length == 2) {
     ip = args[0];
     port = Integer.parseInt(args[1]);
   }
   ServerSocket ss = new ServerSocket();
   ss.bind(new InetSocketAddress(ip, port));
   Socket s;
   while (true) {
     s = ss.accept();
     BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
     PrintWriter out = new PrintWriter(s.getOutputStream(), true);
     // waits for data and reads it in until connection dies
     // readLine() blocks until the server receives a new line from client
     String str;
     while ((str = in.readLine()) != null) {
       if (str.equals("!!")) {
         System.exit(0);
       }
       out.println(str);
     }
   }
 }
Ejemplo n.º 21
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;
  }
  public static void main(String[] args) {

    try {
      System.out.println("Creando socket servidor");

      ServerSocket serverSocket = new ServerSocket();

      System.out.println("Realizando el enlace");
      InetSocketAddress addr = new InetSocketAddress("localhost", 5555);
      serverSocket.bind(addr);

      System.out.println("Aceptando conexiones");
      Socket newSocket = serverSocket.accept();
      System.out.println("Conexión recibida");

      InputStream is = newSocket.getInputStream();
      OutputStream os = newSocket.getOutputStream();

      byte[] mensaje = new byte[25];
      is.read(mensaje);

      System.out.println("Mensaje recibido: " + new String(mensaje));
      System.out.println("Cerrando el nuevo socket");

      newSocket.close();

      System.out.println("Cerrando el socket servidor");
      serverSocket.close();

      System.out.println("Terminado");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 23
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);
    }
  }
  /**
   * Initializes the serversocket and the multiplexer.
   *
   * @param selectorCreator The selector creator that will be used for creating a selector for the
   *     multiplexer.
   */
  private void init(SelectorCreator selectorCreator) {
    try {
      ServerSocketChannel channel = ServerSocketChannel.open();
      ServerSocket serverSocket = channel.socket();

      // Set the preference to bandwidth > short connection time && latency (only large messages
      // will be send / received here).
      serverSocket.setPerformancePreferences(0, 0, 2);

      serverSocket.bind(null);
      Config.setUsingPort(serverSocket.getLocalPort());

      channel.configureBlocking(false);
      selector = selectorCreator.getSelector();
      channel.register(selector, SelectionKey.OP_ACCEPT);

      ToolDataHandlerFactory toolDataHandlerFactory =
          new ToolDataHandlerFactory(InterToolDataHandler.class);
      multiplexer =
          new MultiThreadedMultiplexer(
              selectorCreator, Multiplexer.SERVERMODE, toolDataHandlerFactory);
      multiplexer.setDaemon(true);
      multiplexer.start();
    } catch (IOException ioex) {
      Logger.getInstance()
          .log(
              "An IOException occured while initializing the MultiplexingClientServer.",
              Logger.ERROR,
              ioex);
    }
  }
Ejemplo n.º 25
0
  /**
   * Test of a large write on a socket to understand what happens when the write is greater than the
   * combined size of the client send buffer and the server receive buffer and the server side of
   * the socket is either not accepted or already shutdown.
   *
   * @throws IOException
   * @throws InterruptedException
   */
  public void testDirectSockets_largeWrite_NotAccepted() throws IOException, InterruptedException {

    final Random r = new Random();

    // Get a socket addresss for an unused port.
    final InetSocketAddress serverAddr = new InetSocketAddress(getPort(0));

    // First our ServerSocket
    final ServerSocket ss = new ServerSocket();
    try {

      // Size of the server socket receive buffer.
      final int receiveBufferSize = ss.getReceiveBufferSize();

      // Allocate buffer twice as large as the receive buffer.
      final byte[] largeBuffer = new byte[receiveBufferSize * 10];

      if (log.isInfoEnabled()) {
        log.info(
            "receiveBufferSize=" + receiveBufferSize + ", largeBufferSize=" + largeBuffer.length);
      }

      // fill buffer with random data.
      r.nextBytes(largeBuffer);

      // bind the ServerSocket to the specified port.
      ss.bind(serverAddr);

      // Now the first Client SocketChannel
      final SocketChannel cs = SocketChannel.open();
      try {
        /*
         * Note: true if connection made. false if connection in
         * progress.
         */
        final boolean immediate = cs.connect(serverAddr);
        if (!immediate) {
          // Did not connect immediately, so finish connect now.
          if (!cs.finishConnect()) {
            fail("Did not connect.");
          }
        }

        /*
         * Attempt to write data. The server socket is not yet accepted.
         * This should hit a timeout.
         */
        assertTimeout(10L, TimeUnit.SECONDS, new WriteBufferTask(cs, ByteBuffer.wrap(largeBuffer)));

        accept(ss);

      } finally {
        cs.close();
      }

    } finally {

      ss.close();
    }
  }
 public static boolean running() {
   synchronized (lock) {
     InetAddress[] addresses;
     try {
       addresses = InetUtils.getLocalAddresses();
     } catch (SocketException ex) {
       Log.e(TAG, "", ex);
       return false;
     }
     for (int i = 0; i < addresses.length; i++) {
       ServerSocket serv;
       try {
         serv = new ServerSocket();
         serv.bind(new InetSocketAddress(addresses[i], PORT));
         serv.close();
       } catch (BindException ex) {
         // Log.e(TAG, "", ex);
         Log.i(TAG, "Detected running receiver on " + addresses[i]);
         return true;
       } catch (IOException ex) {
         Log.e(TAG, "", ex);
       }
     }
     return false;
   }
 }
  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();
  }
 public ServerThread(InetAddress addr, ReceiverService service) throws IOException {
   this.addr = addr;
   this.service = service;
   serverSocket = new ServerSocket();
   serverSocket.bind(new InetSocketAddress(addr, PORT));
   thread = new Thread(this);
   count++;
 }
  public void bad() throws Throwable {
    if (IO.static_returns_t_or_f()) {
      ServerSocket sock1 = new ServerSocket();
      sock1.bind(new InetSocketAddress(15000));
      ServerSocket sock2 = new ServerSocket();
      sock2.bind(new InetSocketAddress("localhost", 15000)); /* FLAW - This will bind a second
	   Socket to port 15000, but only for connections from localhost */
    } else {

      ServerSocket sock1 = new ServerSocket();
      sock1.bind(new InetSocketAddress(15000));

      ServerSocket sock2 = new ServerSocket();
      sock2.bind(new InetSocketAddress("localhost", 15001)); /* FIX - This will bind the second
	   Socket to a different port */
    }
  }
  /* good1() changes the "if" so that both branches use the GoodSink */
  private void good1() throws Throwable {
    if (IO.static_returns_t_or_f()) {
      ServerSocket sock1 = new ServerSocket();
      sock1.bind(new InetSocketAddress(15000));
      ServerSocket sock2 = new ServerSocket();
      sock2.bind(new InetSocketAddress("localhost", 15001)); /* FIX - This will bind the second
	   Socket to a different port */
    } else {

      ServerSocket sock1 = new ServerSocket();
      sock1.bind(new InetSocketAddress(15000));

      ServerSocket sock2 = new ServerSocket();
      sock2.bind(new InetSocketAddress("localhost", 15001)); /* FIX - This will bind the second
	   Socket to a different port */
    }
  }