public FileTransferProcessor(
     int upload_port, int download_port, String base_path, String allowFromDomains)
     throws IOException {
   super("File transfer processor");
   CrossDomainFile = CrossDomainFile.replace("<domains>", allowFromDomains);
   Path = base_path;
   UploadGateKeeper = new ServerSocket(upload_port);
   UploadGateKeeper.setSoTimeout(1);
   DownloadGateKeeper = new ServerSocket(download_port);
   DownloadGateKeeper.setSoTimeout(1);
   PolicyGateKeeper = new ServerSocket(843);
   PolicyGateKeeper.setSoTimeout(1);
   FileUploadProc = new FileUploadProcessor(UploadItems);
   FileDownloadProc = new FileDownloadProcessor(DownloadItems);
 }
    @Override
    public void run() {

      List<Socket> inProgress = new ArrayList<>();
      ServerSocketFactory factory = ServerSocketFactory.getDefault();

      try {
        ss = factory.createServerSocket(0);
        ss.setSoTimeout(5000);

        socketReadyLatch.countDown();
        while (!interrupted()) {
          inProgress.add(ss.accept()); // eat socket
        }
      } catch (java.net.SocketTimeoutException expected) {
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          ss.close();
        } catch (IOException ignored) {
        }
        for (Socket s : inProgress) {
          try {
            s.close();
          } catch (IOException ignored) {
          }
        }
      }
    }
  /** @tests java.net.ServerSocket#ServerSocket(int, int) */
  public void test_ConstructorII() throws IOException {
    try {
      s = new ServerSocket(0, 10);
      s.setSoTimeout(2000);
      startClient(s.getLocalPort());
      sconn = s.accept();
    } catch (InterruptedIOException e) {
      return;
    }

    ServerSocket s1 = new ServerSocket(0);
    try {
      try {
        ServerSocket s2 = new ServerSocket(s1.getLocalPort());
        s2.close();
        fail("Was able to create two serversockets on same port");
      } catch (BindException e) {
        // Expected
      }
    } finally {
      s1.close();
    }

    s1 = new ServerSocket(0);
    int allocatedPort = s1.getLocalPort();
    s1.close();
    s1 = new ServerSocket(allocatedPort);
    s1.close();
  }
예제 #4
0
 @SuppressWarnings("unchecked")
 @Override
 public void run() {
   try {
     ListeningSocket.setSoTimeout(ListeningTimeout);
     // .
     try {
       while (!Canceller.flCancel) {
         Socket ClientSocket;
         try {
           ClientSocket = ListeningSocket.accept();
           // . start new session
           new TClientSession(this, ClientSocket);
         } catch (SocketTimeoutException E) {
         }
       }
     } finally {
       ArrayList<TClientSession> _ClientSessions;
       synchronized (ClientSessions) {
         _ClientSessions = (ArrayList<TClientSession>) ClientSessions.clone();
       }
       for (int I = 0; I < _ClientSessions.size(); I++) _ClientSessions.get(I).Finalize();
     }
   } catch (Throwable T) {
     if (!Canceller.flCancel) {
       if (ExceptionHandler != null) ExceptionHandler.DoOnException(T);
     }
   }
 }
예제 #5
0
  public void run() {
    try {
      providerSocket = new ServerSocket(port, 10);
      providerSocket.setSoTimeout(5000);
      while (!stopServer) {
        try {
          connection = providerSocket.accept();
        } catch (SocketTimeoutException e) {
          log.info("........Socket is timed out..........");
          continue;
        }
        Reader reader = new Reader();
        reader.connectionReceived = this.connection;
        new Thread(reader).start();
      }

    } catch (IOException ioException) {
      ioException.printStackTrace();
    } finally {
      try {
        providerSocket.close();
      } catch (Exception e) {

      }
    }
    log.info("Closing connection");
  }
예제 #6
0
  /**
   * Checks that the certificate is compatible with the enabled cipher suites. If we don't check
   * now, the JIoEndpoint can enter a nasty logging loop. See bug 45528.
   */
  private void checkConfig() throws IOException {
    // Create an unbound server socket
    ServerSocket socket = sslProxy.createServerSocket();
    initServerSocket(socket);

    try {
      // Set the timeout to 1ms as all we care about is if it throws an
      // SSLException on accept.
      socket.setSoTimeout(1);

      socket.accept();
      // Will never get here - no client can connect to an unbound port
    } catch (SSLException ssle) {
      // SSL configuration is invalid. Possibly cert doesn't match ciphers
      IOException ioe = new IOException(sm.getString("jsse.invalid_ssl_conf", ssle.getMessage()));
      ioe.initCause(ssle);
      throw ioe;
    } catch (Exception e) {
      /*
       * Possible ways of getting here
       * socket.accept() throws a SecurityException
       * socket.setSoTimeout() throws a SocketException
       * socket.accept() throws some other exception (after a JDK change)
       *      In these cases the test won't work so carry on - essentially
       *      the behaviour before this patch
       * socket.accept() throws a SocketTimeoutException
       *      In this case all is well so carry on
       */
    } finally {
      // Should be open here but just in case
      if (!socket.isClosed()) {
        socket.close();
      }
    }
  }
예제 #7
0
  /**
   * Create a new instance from the given {@link ServerSocket}
   *
   * @param socket the {@link ServerSocket} which is used by this instance
   */
  public OioServerSocketChannel(ServerSocket socket) {
    super(null);
    if (socket == null) {
      throw new NullPointerException("socket");
    }

    boolean success = false;
    try {
      socket.setSoTimeout(SO_TIMEOUT);
      success = true;
    } catch (IOException e) {
      throw new ChannelException("Failed to set the server socket timeout.", e);
    } finally {
      if (!success) {
        try {
          socket.close();
        } catch (IOException e) {
          if (logger.isWarnEnabled()) {
            logger.warn("Failed to close a partially initialized socket.", e);
          }
        }
      }
    }
    this.socket = socket;
    config = new DefaultOioServerSocketChannelConfig(this, socket);
  }
  /** Test of TCP socket programming. */
  public void listen() {
    ServerSocket socket = null;

    try {
      socket = new ServerSocket(PORT_NO);
      System.out.println("Opened server socket");
      socket.setSoTimeout(TIMEOUT);
      connection = socket.accept();
      System.out.println("Server: Received connection from port " + connection.getPort());
      System.out.println("Server: local port: " + connection.getLocalPort());

      ObjectInputStream iStream = new ObjectInputStream(connection.getInputStream());
      MessageObject message = (MessageObject) iStream.readObject();

      System.out.println("message received... by server");
      System.out.println(
          "Server: received object, item=" + message.getItem() + " count: " + message.getCount());

      // sendResponse("'Acknowledging message: object, item=" + message.getItem() + " count: "
      //		+ message.getCount()+"'");
      connection.close();
      socket.close();

    } catch (SocketTimeoutException ste) {
      System.out.println("Timed out after " + TIMEOUT + " ms");
    } catch (Exception e) {
      System.out.println(e.getClass().getName() + " at server: " + e.getMessage());
    }
  } /*
예제 #9
0
  @Override
  public void run() {
    try {
      // Init socket
      serverSocket = new ServerSocket(portNumber);
      serverSocket.setSoTimeout(Configuration.SOCKET_WAIT_TIMEOUT);

      while (_continue) {
        try {
          // Listen
          socket = serverSocket.accept();
          ois = new ObjectInputStream(socket.getInputStream());
          while (null != (objectReceived = (T) ois.readObject())) {
            String[] parts = socket.getRemoteSocketAddress().toString().replace("/", "").split(":");
            Log.e("omar", "--------------------------------------------------");

            Log.e("omar", parts[0]);
            Log.e("omar", "--------------------------------------------------");

            onConsume.onConsume(objectReceived, parts[0]);
          }
        } catch (SocketTimeoutException | EOFException ex) {
        } catch (NullPointerException ex) {
          ex.printStackTrace();
        }
      }
      socket.close();
    } catch (NullPointerException ex) {
    } catch (IOException | ClassNotFoundException ex) {
      ex.printStackTrace();
    }
  }
예제 #10
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);
   }
 }
예제 #11
0
  /** Main loop of the SMTP server. */
  public void run() {
    stopped = false;
    try {
      try {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5
        // seconds
      } finally {
        synchronized (this) {
          // Notify when server socket has been created
          notifyAll();
        }
      }

      // Server: loop until stopped
      while (!isStopped()) {
        // Start server socket and listen for client connections
        Socket socket = null;
        try {
          socket = serverSocket.accept();
        } catch (Exception e) {
          if (socket != null) {
            socket.close();
          }
          continue; // Non-blocking socket timeout occurred: try
          // accept() again
        }

        // Get the input and output streams
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream());

        synchronized (this) {
          /*
           * We synchronize over the handle method and the list update
           * because the client call completes inside the handle
           * method and we have to prevent the client from reading the
           * list until we've updated it. For higher concurrency, we
           * could just change handle to return void and update the
           * list inside the method to limit the duration that we hold
           * the lock.
           */
          List<SmtpMessage> msgs = handleTransaction(out, input);
          receivedMail.addAll(msgs);
        }
        socket.close();
      }
    } catch (Exception e) {
      // TODO Should throw an appropriate exception here.
      e.printStackTrace();
    } finally {
      if (serverSocket != null) {
        try {
          serverSocket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
예제 #12
0
 private void createServerSocket() {
   try {
     serverSocket = new ServerSocket(PORT);
     serverSocket.setSoTimeout(20000);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /** @tests java.net.ServerSocket#setSoTimeout(int) */
  public void test_setSoTimeoutI() throws IOException {
    // Timeout should trigger and throw InterruptedIOException
    try {
      s = new ServerSocket(0);
      s.setSoTimeout(100);
      s.accept();
    } catch (InterruptedIOException e) {
      assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
      return;
    }

    // Timeout should not trigger in this case
    s = new ServerSocket(0);
    startClient(s.getLocalPort());
    s.setSoTimeout(10000);
    sconn = s.accept();
  }
 public void run() {
   try {
     try {
       listeningSocket.setSoTimeout(10000);
     } catch (SocketException e) {
       // There was a TCP error, lets print the stack trace
       e.printStackTrace();
       return;
     }
     while (!done) {
       Socket conn = null;
       synchronized (ProxyProcess.this) {
         while (transfers <= 0 && !done) {
           transfers = -1;
           try {
             ProxyProcess.this.wait();
           } catch (InterruptedException e) {
             /* Do nothing */
           }
         }
       }
       if (done) {
         break;
       }
       try {
         synchronized (listeningSocket) {
           conn = listeningSocket.accept();
         }
         if (conn == null) {
           continue;
         }
         String digest = establishSocks5UploadConnection(conn);
         synchronized (connectionMap) {
           connectionMap.put(digest, conn);
         }
       } catch (SocketTimeoutException e) {
         /* Do Nothing */
       } catch (IOException e) {
         /* Do Nothing */
       } catch (XMPPException e) {
         e.printStackTrace();
         if (conn != null) {
           try {
             conn.close();
           } catch (IOException e1) {
             /* Do Nothing */
           }
         }
       }
     }
   } finally {
     try {
       listeningSocket.close();
     } catch (IOException e) {
       /* Do Nothing */
     }
   }
 }
예제 #15
0
 public CMPPXMLExchanger(int nPort) throws IOException {
   super("CMPPXMLExchanger");
   m_input = new CMPPPacketQueue();
   m_output = new CMPPPacketQueue();
   m_socket = null;
   m_porters = new Vector();
   m_socket = new ServerSocket(nPort);
   m_socket.setSoTimeout((int) TimeConfig.DEFAULT_LISTEN_TIMEOUT);
 }
예제 #16
0
  private void doAccept() throws IOException {
    Socket s = null;
    final long startTime = System.currentTimeMillis();

    while (true) {
      s = ss.accept();
      if (s.getInetAddress().equals(msg.ip)) {
        // got the connection from the right host
        // Close listenning socket.
        ss.close();
        break;
      } else if (ss instanceof SocksServerSocket) {
        // We can't accept more then one connection
        s.close();
        ss.close();
        throw new SocksException(SocksProxyBase.SOCKS_FAILURE);
      } else {
        if (acceptTimeout != 0) { // If timeout is not infinit
          final long passed = System.currentTimeMillis() - startTime;
          final int newTimeout = acceptTimeout - (int) passed;

          if (newTimeout <= 0) {
            throw new InterruptedIOException("newTimeout <= 0");
          }
          ss.setSoTimeout(newTimeout);
        }
        s.close(); // Drop all connections from other hosts
      }
    }

    // Accepted connection
    remote_sock = s;
    remote_in = s.getInputStream();
    remote_out = s.getOutputStream();

    // Set timeout
    remote_sock.setSoTimeout(iddleTimeout);

    final InetAddress inetAddress = s.getInetAddress();
    final int port = s.getPort();
    log.info("Accepted from {}:{}", s.getInetAddress(), port);

    ProxyMessage response;

    if (msg.version == 5) {
      final int cmd = SocksProxyBase.SOCKS_SUCCESS;
      Socks5Message socks5Message = new Socks5Message(cmd, inetAddress, port);
      socks5Message.setDnsResolver(dnsResolver);
      response = socks5Message;
    } else {
      final int cmd = Socks4Message.REPLY_OK;
      Socks4Message socks4Message = new Socks4Message(cmd, inetAddress, port);
      socks4Message.setDnsResolver(dnsResolver);
      response = socks4Message;
    }
    response.write(out);
  }
예제 #17
0
  public FileSender(File file, InetAddress client) throws IOException {
    ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
    ssocket = ssocketFactory.createServerSocket();
    ssocket.bind(null);
    ssocket.setSoTimeout(timeout);

    this.file = file;
    this.client = client;
  }
 /** @tests java.net.ServerSocket#getSoTimeout() */
 public void test_getSoTimeout() throws IOException {
   s = new ServerSocket(0);
   try {
     s.setSoTimeout(100);
     assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
   } finally {
     s.close();
   }
 }
 private void createSockets() throws IOException {
   try {
     myService = new ServerSocket(7101);
     myService.setSoTimeout(120000);
   } catch (SocketException e) {
     throw new RuntimeException(
         "Could not create socket. Did you set the android.permission.INTERNET permission in your AndroidManifest.xml",
         e);
   }
 }
예제 #20
0
 public void listen() throws TTransportException {
   // Make sure not to block on accept
   if (serverSocket_ != null) {
     try {
       serverSocket_.setSoTimeout(0);
     } catch (SocketException sx) {
       sx.printStackTrace();
     }
   }
 }
예제 #21
0
파일: Server.java 프로젝트: pbrant/gradle
  /**
   * This sits in a loop and listens for connections. Once a connection has been made, we'll call
   * another function to process it.
   */
  private void listenForConnections() {
    int consecutiveFailures = 0;
    while (!hasRequestedShutdown) {
      Socket socket = null;
      try {
        serverSocket.setSoTimeout(
            2000); // attempt to connect for a few seconds, then try again (so we'll get any
                   // shutdown requests).
        socket = serverSocket.accept();

        clientSocket = new ObjectSocketWrapper(socket);
        protocol.connectionAccepted();
        consecutiveFailures = 0; // reset our consecutive failures.
        serverSocket.setSoTimeout(0);

        processCommunications();

        clientSocket.close();
      } catch (IOException e) {
        consecutiveFailures++;
        if (consecutiveFailures
            >= 20) // if we fail too many times, we'll request to shutdown. It's obviously not
                   // working. This is an arbitrary number.
        {
          requestShutdown();
        }

        if (consecutiveFailures
            > 8) // the first few usually fail while we're waiting for the process to startup.
        {
          logger.error("Accept failed (" + consecutiveFailures + ").");
        }
      } catch (Throwable t) { // something really bad happened, shut down
        logger.error("Listening for connections", t);
        requestShutdown();
      }
    }

    isServerRunning = false;

    stop();
    notifyServerExited();
  }
예제 #22
0
  private void onBind(ProxyMessage msg) throws IOException {
    ProxyMessage response = null;

    if (proxy == null) ss = new ServerSocket(0);
    else ss = new SocksServerSocket(proxy, msg.ip, msg.port);

    ss.setSoTimeout(acceptTimeout);

    log("Trying accept on " + ss.getInetAddress() + ":" + ss.getLocalPort());

    if (msg.version == 5)
      response = new Socks5Message(CProxy.SOCKS_SUCCESS, ss.getInetAddress(), ss.getLocalPort());
    else
      response = new Socks4Message(Socks4Message.REPLY_OK, ss.getInetAddress(), ss.getLocalPort());
    response.write(out);

    mode = ACCEPT_MODE;

    pipe_thread1 = Thread.currentThread();
    pipe_thread2 = new Thread(this);
    pipe_thread2.start();

    // Make timeout infinit.
    sock.setSoTimeout(0);
    int eof = 0;

    try {
      while ((eof = in.read()) >= 0) {
        if (mode != ACCEPT_MODE) {
          if (mode != PIPE_MODE) return; // Accept failed

          remote_out.write(eof);
          break;
        }
      }
    } catch (EOFException eofe) {
      // System.out.println("EOF exception");
      return; // Connection closed while we were trying to accept.
    } catch (InterruptedIOException iioe) {
      // Accept thread interrupted us.
      // System.out.println("Interrupted");
      if (mode != PIPE_MODE) return; // If accept thread was not successfull return.
    } finally {
      // System.out.println("Finnaly!");
    }

    if (eof < 0) // Connection closed while we were trying to accept;
    return;

    // Do not restore timeout, instead timeout is set on the
    // remote socket. It does not make any difference.

    pipe(in, remote_out);
  }
예제 #23
0
  public MITrisPlugin(Display2D display, double framerate) throws IOException {
    super(display, framerate);
    timestep = 1 / framerate;
    width = display.getWidth();
    height = display.getHeight();
    servSock = new ServerSocket(12345);
    servSock.setSoTimeout(20);

    System.out.println("Game paused until client connect");

    gameState = State.IDLE;
  }
예제 #24
0
 @Override
 public void run() {
   try {
     sendServerAddr(getLocalIpAddress(), SERVER_PORT);
     mServerSock.setSoTimeout(3000);
     updateTransportSocket(mServerSock.accept());
   } catch (IOException e) {
     Log.w(TAG, "Unable get accept from client. Send proxy socket.");
     mOutHandler.obtainMessage(DO_NOT_UPDATE_SOCKET).sendToTarget();
   }
   super.run();
 }
예제 #25
0
  /**
   * Begins the thread that waits for new clients. If the server is already in listening mode, this
   * call has no effect.
   *
   * @exception IOException if an I/O error occurs when creating the server socket.
   */
  public final void listen() throws IOException {
    if (!isListening()) {
      if (serverSocket == null) {
        serverSocket = new ServerSocket(getPort(), backlog);
      }

      serverSocket.setSoTimeout(timeout);

      connectionListener = new Thread(this);
      connectionListener.start();
    }
  }
 /** @tests java.net.ServerSocket#ServerSocket(int, int, java.net.InetAddress) */
 public void test_ConstructorIILjava_net_InetAddress() throws UnknownHostException, IOException {
   s = new ServerSocket(0, 10, InetAddress.getLocalHost());
   try {
     s.setSoTimeout(5000);
     startClient(s.getLocalPort());
     sconn = s.accept();
     assertNotNull("Was unable to accept connection", sconn);
     sconn.close();
   } finally {
     s.close();
   }
 }
예제 #27
0
 public static void main(String[] args) throws Exception {
   boolean success = false;
   try {
     ServerSocket sock;
     sock = new ServerSocket(2333);
     sock.setSoTimeout(2);
     sock.accept();
   } catch (InterruptedIOException e) {
     success = true;
   }
   if (!success) throw new RuntimeException("Socket timeout failure.");
 }
예제 #28
0
 public void init() {
   try {
     socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127, 0, 0, 1}));
     socket.setSoTimeout(5000);
     port = socket.getLocalPort();
     Log.d(LOG_TAG, "port " + port + " obtained");
   } catch (UnknownHostException e) {
     Log.e(LOG_TAG, "Error initializing server", e);
   } catch (IOException e) {
     Log.e(LOG_TAG, "Error initializing server", e);
   }
 }
예제 #29
0
 public MockServer start() throws IOException {
   _server = new ServerSocket();
   _server.setSoTimeout(5000);
   _server.bind(new InetSocketAddress("localhost", 0));
   _serverSocketPort = _server.getLocalPort();
   _threads.add(
       new EasyThread() {
         @Override
         void runQuietly() throws Exception {
           runServer();
         }
       }.startThread());
   return this;
 }
예제 #30
0
  private void connectInternal() throws IOException {
    int port = url.getPort();
    int connectTimeout = getConnectTimeout();
    if (port <= 0) {
      port = FTP_PORT;
    }
    if (null == currentProxy || Proxy.Type.HTTP == currentProxy.type()) {
      controlSocket = new Socket();
    } else {
      controlSocket = new Socket(currentProxy);
    }
    InetSocketAddress addr = new InetSocketAddress(hostName, port);
    controlSocket.connect(addr, connectTimeout);
    connected = true;
    ctrlOutput = controlSocket.getOutputStream();
    ctrlInput = controlSocket.getInputStream();
    login();
    setType();
    if (!getDoInput()) {
      cd();
    }

    try {
      acceptSocket = new ServerSocket(0);
      dataPort = acceptSocket.getLocalPort();
      /* Cannot set REUSEADDR so we need to send a PORT command */
      port();
      if (connectTimeout == 0) {
        // set timeout rather than zero as before
        connectTimeout = 3000;
      }
      acceptSocket.setSoTimeout(getConnectTimeout());
      if (getDoInput()) {
        getFile();
      } else {
        sendFile();
      }
      dataSocket = acceptSocket.accept();
      dataSocket.setSoTimeout(getReadTimeout());
      acceptSocket.close();
    } catch (InterruptedIOException e) {
      throw new IOException(Msg.getString("K0095")); // $NON-NLS-1$
    }
    if (getDoInput()) {
      inputStream =
          new FtpURLInputStream(
              new BufferedInputStream(dataSocket.getInputStream()), controlSocket);
    }
  }