@Override
  public void run() {
    try {
      if (socket != null && !socket.isClosed()) {
        while (true) {
          Log.i("Server Started", "Server Started");
          fileSocket = socket.accept();
          Log.i("RF Sever Accepted", "accepted saving now");
          saveFile(fileSocket);

          new Thread(new SendEndMsg(Home.current)).start(); /*to send free me msg*/
        }
      } else Log.i("Error", "file Port Already Bind Close Reconnect");
    } catch (IOException e) {
      Log.i("RFSever Accepted", "IO");
      e.printStackTrace();
    } catch (Exception e) {
      Log.i("RFSever Accepted", "EX");
      e.printStackTrace();
    }
    {
      Log.i("RF FAIL", "Is closed check");
      if (socket != null && !socket.isClosed()) {
        try {
          Log.i("FAIL", "Closing");
          socket.close();
        } catch (IOException e) {

          Log.i("FAIL", "Fail to close socket");
          e.printStackTrace();
        }
      }
    }
  }
示例#2
0
 @Test
 public void testCloseQuietlyServerSocketOpen() throws IOException {
   final ServerSocket s = new ServerSocket(0);
   assertFalse(s.isClosed());
   IOUtils.closeQuietly(s);
   assertTrue(s.isClosed());
 }
  /** @tests java.net.ServerSocket#isClosed() */
  public void test_isClosed() throws IOException {
    InetAddress addr = InetAddress.getLocalHost();
    ServerSocket serverSocket = new ServerSocket(0, 5, addr);

    // validate isClosed returns expected values
    assertFalse("Socket should indicate it is not closed(1):", serverSocket.isClosed());
    serverSocket.close();
    assertTrue("Socket should indicate it is closed(1):", serverSocket.isClosed());

    // now do with some of the other constructors
    serverSocket = new ServerSocket(0);
    assertFalse("Socket should indicate it is not closed(1):", serverSocket.isClosed());
    serverSocket.close();
    assertTrue("Socket should indicate it is closed(1):", serverSocket.isClosed());

    serverSocket = new ServerSocket(0, 5, addr);
    assertFalse("Socket should indicate it is not closed(1):", serverSocket.isClosed());
    serverSocket.close();
    assertTrue("Socket should indicate it is closed(1):", serverSocket.isClosed());

    serverSocket = new ServerSocket(0, 5);
    assertFalse("Socket should indicate it is not closed(1):", serverSocket.isClosed());
    serverSocket.close();
    assertTrue("Socket should indicate it is closed(1):", serverSocket.isClosed());
  }
 @AfterClass
 public static void tearDownClass() {
   Logger.info(
       HttpClientUtilsTest.class,
       "============= [tearDownClass]global take time milliseconds: "
           + (System.currentTimeMillis() - g_beginTime));
   if (httpServer != null) {
     httpServer.stop(0);
   }
   if (httpServer2 != null) {
     httpServer2.stop(0);
   }
   if (serverSocket != null && !serverSocket.isClosed()) {
     try {
       serverSocket.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   for (Socket s : clientSockets) {
     try {
       if (!s.isClosed()) s.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
  /**
   * 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();
      }
    }
  }
  /** {@inheritDoc} */
  public Object getOption(SocketOption name) throws IOException {
    if (!(name instanceof StandardSocketOption)) {
      throw new IllegalArgumentException("Unsupported option " + name);
    }

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

    try {
      switch (stdOpt) {
        case SO_RCVBUF:
          return socket.getReceiveBufferSize();

        case SO_REUSEADDR:
          return socket.getReuseAddress();

        default:
          throw new IllegalArgumentException("Unsupported option " + name);
      }
    } catch (SocketException e) {
      if (socket.isClosed()) {
        throw Util.initCause(new ClosedChannelException(), e);
      }
      throw e;
    }
  }
示例#7
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);
        }
      }
    }
  }
  @Override
  protected int doReadMessages(MessageList<Object> buf) throws Exception {
    if (socket.isClosed()) {
      return -1;
    }

    try {
      Socket s = socket.accept();
      try {
        if (s != null) {
          buf.add(new OioSocketChannel(this, s));
          return 1;
        }
      } catch (Throwable t) {
        logger.warn("Failed to create a new channel from an accepted socket.", t);
        if (s != null) {
          try {
            s.close();
          } catch (Throwable t2) {
            logger.warn("Failed to close a socket.", t2);
          }
        }
      }
    } catch (SocketTimeoutException e) {
      // Expected
    }
    return 0;
  }
  /** {@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;
  }
  /** {@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;
  }
示例#11
0
  public static void main(String args[]) throws Exception {
    int count = 0;
    ServerSocket serv = null;
    InputStream in = null;
    OutputStream out = null;
    Socket sock = null;
    int clientId = 0;
    Map<Integer, Integer> totals = new HashMap<Integer, Integer>();

    try {
      serv = new ServerSocket(8888);
    } catch (Exception e) {
      e.printStackTrace();
    }
    while (serv.isBound() && !serv.isClosed()) {
      System.out.println("Ready...");
      try {
        sock = serv.accept();
        in = sock.getInputStream();
        out = sock.getOutputStream();

        char c = (char) in.read();

        System.out.print("Server received " + c);
        switch (c) {
          case 'r':
            clientId = in.read();
            totals.put(clientId, 0);
            out.write(0);
            break;
          case 't':
            clientId = in.read();
            int x = in.read();
            System.out.print(" for client " + clientId + " " + x);
            Integer total = totals.get(clientId);
            if (total == null) {
              total = 0;
            }
            totals.put(clientId, total + x);
            out.write(totals.get(clientId));
            break;
          default:
            int x2 = in.read();
            int y = in.read();
            System.out.print(" " + x2 + " " + y);
            out.write(x2 + y);
        }
        System.out.println("");
        out.flush();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (out != null) out.close();
        if (in != null) in.close();
        if (sock != null) sock.close();
      }
    }
  }
 /** Shutdown proxy server and all active agent-proxy instances. */
 public void shutdown() {
   if (proxySocket != null && !proxySocket.isClosed()) {
     try {
       proxySocket.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
示例#13
0
 public static void closeSocket(ServerSocket paramServerSocket) {
   if ((paramServerSocket != null) && (!paramServerSocket.isClosed())) {}
   try {
     paramServerSocket.close();
     return;
   } catch (IOException localIOException) {
     localIOException.printStackTrace();
   }
 }
示例#14
0
 public static void closeSocket(ServerSocket serverSocket) {
   if (serverSocket == null || serverSocket.isClosed()) return;
   try {
     serverSocket.close();
     return;
   } catch (IOException var1_1) {
     var1_1.printStackTrace();
     return;
   }
 }
 public void disconnect() {
   myShouldAccept = false;
   if (myServerSocket != null && !myServerSocket.isClosed()) {
     try {
       myServerSocket.close();
     } catch (IOException ignore) {
     }
     myServerSocket = null;
   }
 }
示例#16
0
 /** 关闭作业监听服务. */
 public void close() {
   closed = true;
   if (null != serverSocket && !serverSocket.isClosed()) {
     try {
       serverSocket.close();
     } catch (final IOException ex) {
       log.warn(ex.getMessage());
     }
   }
 }
 protected void stopRequested() {
   try {
     if (!server.isClosed()) {
       server.close();
     }
   } catch (IOException e) {
     // A least I have tried...
     // This is only to kick server.accept() out of its block - if there is a
     // problem, the accept has already failed
   }
 };
示例#18
0
 @Override
 public void run() {
   // TODO Auto-generated method stub
   while (!connection.isClosed()) {
     try {
       Socket newUser = connection.accept();
       UserConnection thread = new UserConnection(newUser, callbacks);
       thread.run();
     } catch (IOException e) {
     }
   }
 }
示例#19
0
  /*
   * Closes sockets to terminate contact with the server
   */
  void closeSocket() {
    try {
      in.close();
      out.close();
      socket.close(); // NullPointerException
      ss.close();
      if (ss != null && !ss.isClosed()) ss.close();
    } catch (Exception e) {
      throw new RuntimeException("Error closing server", e);
      // e.printStackTrace();
    }

    System.exit(0);
  }
示例#20
0
 protected void doDispose() {
   try {
     if (serverSocket != null && !serverSocket.isClosed()) {
       if (logger.isDebugEnabled()) {
         logger.debug("Closing: " + serverSocket);
       }
       serverSocket.close();
     }
     serverSocket = null;
   } catch (Exception e) {
     logger.error(new DisposeException(TcpMessages.failedToCloseSocket(), e, this));
   }
   logger.info("Closed Tcp port");
 }
 @Override
 public void close() {
   if (!myServerSocket.isClosed()) {
     try {
       myServerSocket.close();
     } catch (IOException e) {
       LOG.warn("Error closing socket", e);
     }
   }
   if (myDebuggerReader != null) {
     myDebuggerReader.stop();
   }
   fireCloseEvent();
 }
  @Override
  public void close() {
    for (ProcessDebugger d : allDebuggers()) {
      d.close();
    }
    disposeAcceptor();

    if (!myServerSocket.isClosed()) {
      try {
        myServerSocket.close();
      } catch (IOException e) {
        LOG.warn("Error closing socket", e);
      }
    }
  }
示例#23
0
  public static void main(String[] args) throws IOException {
    final ServerSocket ss = new ServerSocket(PORT);

    while (!ss.isClosed()) {
      Socket inboundConnection = ss.accept();

      BufferedReader in =
          new BufferedReader(new InputStreamReader(inboundConnection.getInputStream()));
      System.out.println("SERVER received: " + in.readLine());

      PrintWriter out = new PrintWriter(inboundConnection.getOutputStream(), true);
      out.println("PONG");

      inboundConnection.close();
    }
  }
  /** Stop the listener */
  public void stopListening(ListenKey listener) throws IOException {
    if (!(listener instanceof SocketListenKey)) {
      throw new IllegalArgumentException("Invalid listener");
    }

    synchronized (listener) {
      ServerSocket ss = ((SocketListenKey) listener).socket();

      // if the ServerSocket has been closed it means
      // the listener is invalid
      if (ss.isClosed()) {
        throw new IllegalArgumentException("Invalid listener");
      }
      ss.close();
    }
  }
示例#25
0
  public void run() {
    while (srv_sock != null && !srv_sock.isClosed()) {
      try {
        final Socket sock = srv_sock.accept();
        sockets.add(sock);

        createInterpreter();

        new Thread() {
          public void run() {
            try {
              InputStream input = sock.getInputStream();
              OutputStream out = sock.getOutputStream();
              BufferedReader reader = new BufferedReader(new InputStreamReader(input));

              while (!sock.isClosed()) {
                String line = reader.readLine();
                if (line == null || line.length() == 0) continue;
                try {
                  Object retval = interpreter.eval(line);
                  if (retval != null) {
                    String rsp = retval.toString();
                    byte[] buf = rsp.getBytes();
                    out.write(buf, 0, buf.length);
                    out.flush();
                  }
                  if (log.isTraceEnabled()) {
                    log.trace(line);
                    if (retval != null) log.trace(retval);
                  }
                } catch (EvalError evalError) {
                  evalError.printStackTrace();
                }
              }
            } catch (IOException e) {
              e.printStackTrace();
            } finally {
              Util.close(sock);
              sockets.remove(sock);
            }
          }
        }.start();
      } catch (IOException e) {
      }
    }
  }
示例#26
0
 @Override
 public void run() {
   try {
     while (!listener.isClosed()) {
       // Wait for and accept all incoming connections.
       Socket socket = getListener().accept();
       if (activeConnectionAddresses.contains(socket.getInetAddress().getHostAddress())) {
         socket.close();
       } else {
         activeConnectionAddresses.add(socket.getInetAddress().getHostAddress());
       }
       // Create a new thread to handle the request.
       (new Thread(new RequestHandler(socket, this))).start();
     }
   } catch (IOException ignored) {
   }
 }
示例#27
0
  public void startServer() throws IOException {
    final ServerSocket localServerSocket = createServerSocket();

    while (isRunning()) {
      final Socket socket;
      try {
        socket = localServerSocket.accept();
      } catch (SocketException e) {
        if (!localServerSocket.isClosed()) throw e;
        break;
      }

      final ClientHandler client = new ClientHandler(this, socket);
      clients.add(client);
      new Thread(client).start();
    }
  }
示例#28
0
 private void acceptConnections() {
   while (!_mySocket.isClosed()) {
     try {
       if (port == NetworkConfiguration.DEVICE_PORT) {
         Logger.info("[GestureServer] Accepting device connections");
         acceptConnection(_mySocket.accept());
         return; // only one of these
       }
       Logger.info("[GestureServer] Accepting client connections");
       acceptConnection(_mySocket.accept());
     } catch (IOException e) {
       Logger.error("[GestureServer] Failed to establish connection on port " + port);
       e.printStackTrace();
     }
   }
   Logger.info("[GestureServer] Socket Closed on port " + port);
 }
示例#29
0
 /** Close any sockets associated with the current transfer mode. */
 private void closeTransferMode() {
   try {
     if (passive) {
       if (pasvSock != null && !pasvSock.isClosed()) {
         debug("Closing passive connection");
         pasvIn.close();
         pasvSock.close();
       }
     } else {
       if (activeSock != null && !activeSock.isClosed()) {
         debug("Closing active connection");
         activeSock.close();
       }
     }
   } catch (IOException e) {
     System.err.println("Error closing transfer mode: " + e.getMessage());
   }
 }
示例#30
0
 public void run() {
   this.runningFlag = true;
   restart();
   while (runningFlag) {
     try {
       if (serverSocket.isBound() && !serverSocket.isClosed()) {
         Socket remote = serverSocket.accept();
         // remote is now the connected socket
         System.out.println("Connection, sending data.");
         scheduleRequest(remote);
       } else {
         Thread.sleep(1000);
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }