Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

InputStream.available() returns 0 after securing a plain Socket with TLS

843790Aug 29 2009 — edited Aug 30 2009
After I turn a plain Socket-connection into a connection which is secured via TLS SSLSocket.getInputStream.available() returns 0 although there are bytes available in the stream. I could overcome the problem with some kind of "active waiting" which means that I read 0 bytes from the stream:
int iBlockingTimeMS = 500;
int avail; //number of available bytes in input stream
		try {
			avail = input.available();
			if ( avail <= 0 ) {
				//active waiting:
				input.read(new byte[0]);
				Thread.sleep( iBlockingTimeMS );
			}
		} catch (InterruptedException e) {}
		
		//retry after active waiting
		avail = input.available(); //<-- fetch correct value
The second call of InputStream.available() returns the correct value but the workaround has a big drawback since the method blocks (because of InputStream.read()) if really no content is available.
Here's how I secure the plain socket:
	/**
	 * handles a TLS negotiation request from the client
	 *
	 */
	private void handleTLS () throws XMLSyntaxException, IOException, ConnectionClosedException, TimeoutException, EndOfBufferException {
		System.out.println("Securing socket...");
		
		// generate ssl security on top of the existing connection
		SSLSocket secured = (SSLSocket)socketFactory.createSocket(
				socket,
				socket.getInetAddress().getHostAddress(),
				socket.getPort(),
				false );
		secured.setUseClientMode( false );
		secured.startHandshake();
		
		// ok, wait for new content to arrive
		// don't know, why I have to use this kind of 'active' waiting?!?
		// but if i wait until available gets bigger 0 without reading nothing from the input stream
		// i will wait forever
		while ( secured.getInputStream().available() <= 0 ) {
			try
			{
				// read nothing
				secured.getInputStream().read ( new byte[0] );
				Thread.sleep(200) ;
			}
			catch (InterruptedException e)
			{}
		}
		
		socket = secured;
		input = socket.getInputStream();
		
		System.out.println("Socket is secured!");
	}
It's quite strange that I can omit "active waiting" if I don't use TLS and that Inputstream.available() works perfectly in that case. Has anyone experienced this problem before?

Thanks for reading!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 27 2009
Added on Aug 29 2009
4 comments
2,854 views