Java Code Examples for java.net.Socket.isClosed()

The following are Jave code examples for showing how to use isClosed() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: ultrasonic   File: SSLSocketFactory.java   Source Code and License Vote up 6 votes
/**
 * Checks whether a socket connection is secure.
 * This factory creates TLS/SSL socket connections
 * which, by default, are considered secure.
 * <br/>
 * Derived classes may override this method to perform
 * runtime checks, for example based on the cypher suite.
 *
 * @param sock the connected socket
 * @return <code>true</code>
 * @throws IllegalArgumentException if the argument is invalid
 */
public boolean isSecure(final Socket sock) throws IllegalArgumentException
{
	if (sock == null)
	{
		throw new IllegalArgumentException("Socket may not be null");
	}

	// This instanceof check is in line with createSocket() above.
	if (!(sock instanceof SSLSocket))
	{
		throw new IllegalArgumentException("Socket not created by this factory");
	}

	// This check is performed last since it calls the argument object.
	if (sock.isClosed())
	{
		throw new IllegalArgumentException("Socket is closed");
	}

	return true;
}
 
Example 2
Project: CrawlerSYS   File: CrawlerServer.java   Source Code and License Vote up 6 votes
public void run() {
		while(!server.isClosed()){
				Socket sk = null;
				try {
					sk = server.accept();
				} catch (IOException e) {
					// TODO Auto-generated catch block
e.printStackTrace();logger.error("Exception",e);
				}
				if(sk!=null&&!sk.isClosed()){
					NodeReceiveThread nrt= new NodeReceiveThread(sk);
					nrt.start();
				}	
		}
		System.out.println("server closed");	
		logger.info("server closed");
	}
 
Example 3
Project: lams   File: MultihomePlainSocketFactory.java   Source Code and License Vote up 6 votes
/**
 * Checks whether a socket connection is secure.
 * This factory creates plain socket connections
 * which are not considered secure.
 *
 * @param sock      the connected socket
 *
 * @return  <code>false</code>
 *
 * @throws IllegalArgumentException if the argument is invalid
 */
public final boolean isSecure(Socket sock)
    throws IllegalArgumentException {

    if (sock == null) {
        throw new IllegalArgumentException("Socket may not be null.");
    }
    // This class check assumes that createSocket() calls the constructor
    // directly. If it was using javax.net.SocketFactory, we couldn't make
    // an assumption about the socket class here.
    if (sock.getClass() != Socket.class) {
        throw new IllegalArgumentException
            ("Socket not created by this factory.");
    }
    // This check is performed last since it calls a method implemented
    // by the argument object. getClass() is final in java.lang.Object.
    if (sock.isClosed()) {
        throw new IllegalArgumentException("Socket is closed.");
    }

    return false;

}
 
Example 4
Project: monarch   File: SocketCloserJUnitTest.java   Source Code and License Vote up 6 votes
/**
 * Verify that a closed SocketCloser will still close an open socket
 */
@Test
public void testClosedSocketCloser() {
  final AtomicBoolean runnableCalled = new AtomicBoolean();
  Runnable r = new Runnable() {
    @Override
    public void run() {
      runnableCalled.set(true);
    }
  };

  final Socket s = createClosableSocket();
  this.socketCloser.close();
  this.socketCloser.asyncClose(s, "A", r);
  WaitCriterion wc = new WaitCriterion() {
    public boolean done() {
      return runnableCalled.get() && s.isClosed();
    }

    public String description() {
      return "runnable was not called or socket was not closed";
    }
  };
  Wait.waitForCriterion(wc, 5000, 10, true);
}
 
Example 5
Project: zabbkit-android   File: MySSLSocketFactory.java   Source Code and License Vote up 6 votes
@Override
public boolean isSecure(Socket sock) throws IllegalArgumentException {
	if (sock == null) {
		throw new IllegalArgumentException("Socket may not be null.");
	}

	if (!(sock instanceof SSLSocket)) {
		throw new IllegalArgumentException("Socket not created by this factory.");
	}

	if (sock.isClosed()) {
		throw new IllegalArgumentException("Socket is closed.");
	}

	return true;

}
 
Example 6
Project: blackbird   File: NetworkConnection.java   Source Code and License Vote up 5 votes
/**
 * Creates a connection using a connected socket
 *
 * @param socket the socket this connection is based on
 * @throws IOException if the socket is either closed, unbound or not connected.
 */
public NetworkConnection(Socket socket) throws IOException {
    if (socket.isClosed() || !socket.isBound() || !socket.isConnected())
        throw new IOException("NetworkConnection expects a not closed, bound and connected socket");

    this.socket = socket;
}
 
Example 7
Project: KeYExperienceReport   File: Client.java   Source Code and License Vote up 5 votes
public Client(final String ip, int port) throws UnknownHostException,
		IOException, ClassNotFoundException {
	Socket socket = new Socket(ip, port);
	ObjectOutputStream outToClient = new ObjectOutputStream(
			socket.getOutputStream());
	ObjectInputStream inFromClient = new ObjectInputStream(
			socket.getInputStream());

	long startTime = System.currentTimeMillis();
	long currentTime = System.currentTimeMillis();
	while (socket.isConnected() && jobs < MAX_JOBS
			&& (currentTime - startTime) < MAX_RUNTIME) {
		jobs++;
		ResultRunnable job = (ResultRunnable) inFromClient.readObject();
		job.setIPAdress(ip);
		job.run();
		Object result = job.getResult();
		try {
			outToClient.writeObject(result);
		} catch (NotSerializableException e) {
			outToClient.writeObject(e);
		}
		currentTime = System.currentTimeMillis();
	}

	if (!socket.isClosed()) {
		restart = true;
	}

	socket.close();
}
 
Example 8
Project: pcloud-networking-java   File: RealConnection.java   Source Code and License Vote up 5 votes
boolean isHealthy(boolean doExtensiveChecks) {
    if (!connected) {
        return false;
    }

    Socket socket;
    BufferedSource source;
    synchronized (this) {
        socket = this.socket;
        source = this.source;
    }
    if (socket == null ||
            source == null ||
            socket.isClosed() ||
            socket.isInputShutdown() ||
            socket.isOutputShutdown()) {
        return false;
    }

    if (doExtensiveChecks) {
        try {
            int readTimeout = socket.getSoTimeout();
            try {
                socket.setSoTimeout(1);
                return !source.exhausted();
            } finally {
                socket.setSoTimeout(readTimeout);
            }
        } catch (SocketTimeoutException ignored) {
            ignored.printStackTrace();
            // Read timed out; socket is good.
        } catch (IOException e) {
            return false; // Couldn't read; socket is closed.
        }
    }

    return true;
}
 
Example 9
Project: AndroidVideoCache   File: HttpProxyCacheServer.java   Source Code and License Vote up 5 votes
private void closeSocket(Socket socket) {
    try {
        if (!socket.isClosed()) {
            socket.close();
        }
    } catch (IOException e) {
        onError(new ProxyCacheException("Error closing socket", e));
    }
}
 
Example 10
Project: owa-notifier   File: InternalWebServer.java   Source Code and License Vote up 5 votes
@Override
public void run() {
	List<Socket> sockets = new ArrayList<Socket>();
	while (this.tokenResponse == null) {
		Socket s;
		try {
			s = this.socket.accept();
			sockets.add(s);
			InternalWebServerTransaction c = new InternalWebServerTransaction(s,this, nonce.toString());
			c.addObserver(this);
		} catch (IOException e) {
			if(e instanceof SocketException) {
				// When user obtain a token closing listen socket cause this exception
				// In this case this is a normal exception
				logger.info("Closing listening socket.");
			} else {
				logger.error("IOException while accepting client requests", e);
			}
			// Close all transcation sockets
			for(Socket transactionSocket: sockets) {
				try {
					if(!transactionSocket.isClosed()) {
						transactionSocket.close();
					}
				} catch (IOException e1) {
					logger.error("IOException while closing client requests", e1);
				}
			}
			serverThread.interrupt();
		}
       }		
	serverThread.interrupt();
}
 
Example 11
Project: LotusCloud   File: PacketClient.java   Source Code and License Vote up 5 votes
public static Packet request(String host, int port, Packet packet) {
    KeyPair keyPair = Crypter.generateKeyPair();

    try {
        Socket socket = new Socket(host, port);

        if (socket.isClosed()) {
            return new ErrorPacket("socket closed");
        }

        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

        out.writeObject(keyPair.getPublic());
        PublicKey publicKey = (PublicKey) in.readObject();

        SecretKey key = Crypter.generateEC(keyPair.getPrivate(), publicKey);

        out.writeObject(Crypter.encrypt(key, Crypter.toByteArray(packet)));
        out.flush();

        Packet response = (Packet) Crypter.toObject(Crypter.decrypt(key, (byte[]) in.readObject()));

        in.close();
        out.close();
        socket.close();

        return response;
    } catch (Exception ex) {
        return new ErrorPacket(ex.getMessage());
    }
}
 
Example 12
Project: lams   File: PlainSocketFactory.java   Source Code and License Vote up 5 votes
/**
 * Checks whether a socket connection is secure.
 * This factory creates plain socket connections
 * which are not considered secure.
 *
 * @param sock      the connected socket
 *
 * @return  <code>false</code>
 *
 * @throws IllegalArgumentException if the argument is invalid
 */
public final boolean isSecure(Socket sock)
    throws IllegalArgumentException {

    if (sock == null) {
        throw new IllegalArgumentException("Socket may not be null.");
    }
    // This check is performed last since it calls a method implemented
    // by the argument object. getClass() is final in java.lang.Object.
    if (sock.isClosed()) {
        throw new IllegalArgumentException("Socket is closed.");
    }
    return false;
}
 
Example 13
Project: lams   File: SSLSocketFactory.java   Source Code and License Vote up 5 votes
/**
 * Checks whether a socket connection is secure.
 * This factory creates TLS/SSL socket connections
 * which, by default, are considered secure.
 * <br/>
 * Derived classes may override this method to perform
 * runtime checks, for example based on the cypher suite.
 *
 * @param sock      the connected socket
 *
 * @return  <code>true</code>
 *
 * @throws IllegalArgumentException if the argument is invalid
 */
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
    if (sock == null) {
        throw new IllegalArgumentException("Socket may not be null");
    }
    // This instanceof check is in line with createSocket() above.
    if (!(sock instanceof SSLSocket)) {
        throw new IllegalArgumentException("Socket not created by this factory");
    }
    // This check is performed last since it calls the argument object.
    if (sock.isClosed()) {
        throw new IllegalArgumentException("Socket is closed");
    }
    return true;
}
 
Example 14
Project: libshout-java   File: Jlibshout.java   Source Code and License Vote up 5 votes
private void init() throws Exception {
  try {
    socket = new Socket(targetHost, targetPort);
    outputStream = socket.getOutputStream();
    PrintWriter out = new PrintWriter(outputStream, false);
    InputStream inputStream = socket.getInputStream();

    // send an HTTP request to the web server
    out.println(String.format("SOURCE %s HTTP/1.0", mounter));
    out.println(String.format("Authorization: Basic %s", HttpRequest.Base64.encode(user + ":" + password)));
    out.println("User-Agent: libshout/2.3.1");
    out.println(String.format("Content-Type: %s", mimeType.getContentType()));
    out.println(String.format("ice-name: %s", iceName));
    out.println("ice-public: 0");
    if (iceDesc != null) {
      out.println(String.format("ice-description: %s", iceDesc));
    }
    out.println();
    out.flush();

    // check if 404
    LineReader lineReader = new LineReader(new InputStreamReader(inputStream));
    String data = lineReader.readLine();

    handleResponse(data);
  } catch (Exception e) {
    if (socket != null && !socket.isClosed()) {
      try {
        socket.close();
      } catch (IOException e1) {
        // skip
      }
    }
    throw e;
  }
}
 
Example 15
Project: monarch   File: SocketCloser.java   Source Code and License Vote up 5 votes
/**
 * Closes the specified socket in a background thread. In some cases we see close hang (see bug
 * 33665). Depending on how the SocketCloser is configured (see ASYNC_CLOSE_WAIT_MILLISECONDS)
 * this method may block for a certain amount of time. If it is called after the SocketCloser is
 * closed then a normal synchronous close is done.
 * 
 * @param sock the socket to close
 * @param address identifies who the socket is connected to
 * @param extra an optional Runnable with stuff to execute in the async thread
 */
public void asyncClose(final Socket sock, final String address, final Runnable extra) {
  if (sock == null || sock.isClosed()) {
    return;
  }
  boolean doItInline = false;
  try {
    synchronized (asyncCloseExecutors) {
      if (isClosed()) {
        // this SocketCloser has been closed so do a synchronous, inline, close
        doItInline = true;
      } else {
        asyncExecute(address, new Runnable() {
          public void run() {
            Thread.currentThread().setName("AsyncSocketCloser for " + address);
            try {
              if (extra != null) {
                extra.run();
              }
              inlineClose(sock);
            } finally {
              Thread.currentThread().setName("unused AsyncSocketCloser");
            }
          }
        });
      }
    }
  } catch (OutOfMemoryError ignore) {
    // If we can't start a thread to close the socket just do it inline.
    // See bug 50573.
    doItInline = true;
  }
  if (doItInline) {
    if (extra != null) {
      extra.run();
    }
    inlineClose(sock);
  }
}
 
Example 16
Project: Mafia   File: GameServer.java   Source Code and License Vote up 5 votes
private void closeSocket(Socket socket) {
	if(!socket.isClosed()) {
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
}
 
Example 17
Project: GitHub   File: MockWebServer.java   Source Code and License Vote up 4 votes
/**
 * Transfer bytes from {@code source} to {@code sink} until either {@code byteCount} bytes have
 * been transferred or {@code source} is exhausted. The transfer is throttled according to {@code
 * policy}.
 */
private void throttledTransfer(MockResponse policy, Socket socket, BufferedSource source,
    BufferedSink sink, long byteCount, boolean isRequest) throws IOException {
  if (byteCount == 0) return;

  Buffer buffer = new Buffer();
  long bytesPerPeriod = policy.getThrottleBytesPerPeriod();
  long periodDelayMs = policy.getThrottlePeriod(TimeUnit.MILLISECONDS);

  long halfByteCount = byteCount / 2;
  boolean disconnectHalfway = isRequest
      ? policy.getSocketPolicy() == DISCONNECT_DURING_REQUEST_BODY
      : policy.getSocketPolicy() == DISCONNECT_DURING_RESPONSE_BODY;

  while (!socket.isClosed()) {
    for (int b = 0; b < bytesPerPeriod; ) {
      // Ensure we do not read past the allotted bytes in this period.
      long toRead = Math.min(byteCount, bytesPerPeriod - b);
      // Ensure we do not read past halfway if the policy will kill the connection.
      if (disconnectHalfway) {
        toRead = Math.min(toRead, byteCount - halfByteCount);
      }

      long read = source.read(buffer, toRead);
      if (read == -1) return;

      sink.write(buffer, read);
      sink.flush();
      b += read;
      byteCount -= read;

      if (disconnectHalfway && byteCount == halfByteCount) {
        socket.close();
        return;
      }

      if (byteCount == 0) return;
    }

    if (periodDelayMs != 0) {
      try {
        Thread.sleep(periodDelayMs);
      } catch (InterruptedException e) {
        throw new AssertionError();
      }
    }
  }
}
 
Example 18
Project: GitHub   File: MockWebServer.java   Source Code and License Vote up 4 votes
/**
 * Transfer bytes from {@code source} to {@code sink} until either {@code byteCount} bytes have
 * been transferred or {@code source} is exhausted. The transfer is throttled according to {@code
 * policy}.
 */
private void throttledTransfer(MockResponse policy, Socket socket, BufferedSource source,
    BufferedSink sink, long byteCount, boolean isRequest) throws IOException {
  if (byteCount == 0) return;

  Buffer buffer = new Buffer();
  long bytesPerPeriod = policy.getThrottleBytesPerPeriod();
  long periodDelayMs = policy.getThrottlePeriod(TimeUnit.MILLISECONDS);

  long halfByteCount = byteCount / 2;
  boolean disconnectHalfway = isRequest
      ? policy.getSocketPolicy() == DISCONNECT_DURING_REQUEST_BODY
      : policy.getSocketPolicy() == DISCONNECT_DURING_RESPONSE_BODY;

  while (!socket.isClosed()) {
    for (int b = 0; b < bytesPerPeriod; ) {
      // Ensure we do not read past the allotted bytes in this period.
      long toRead = Math.min(byteCount, bytesPerPeriod - b);
      // Ensure we do not read past halfway if the policy will kill the connection.
      if (disconnectHalfway) {
        toRead = Math.min(toRead, byteCount - halfByteCount);
      }

      long read = source.read(buffer, toRead);
      if (read == -1) return;

      sink.write(buffer, read);
      sink.flush();
      b += read;
      byteCount -= read;

      if (disconnectHalfway && byteCount == halfByteCount) {
        socket.close();
        return;
      }

      if (byteCount == 0) return;
    }

    if (periodDelayMs != 0) {
      try {
        Thread.sleep(periodDelayMs);
      } catch (InterruptedException e) {
        throw new AssertionError();
      }
    }
  }
}