001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 package org.apache.commons.net.io;
019
020 import java.io.FilterInputStream;
021 import java.io.IOException;
022 import java.io.InputStream;
023 import java.net.Socket;
024
025 /***
026 * This class wraps an input stream, storing a reference to its originating
027 * socket. When the stream is closed, it will also close the socket
028 * immediately afterward. This class is useful for situations where you
029 * are dealing with a stream originating from a socket, but do not have
030 * a reference to the socket, and want to make sure it closes when the
031 * stream closes.
032 * <p>
033 * <p>
034 * @author Daniel F. Savarese
035 * @see SocketOutputStream
036 ***/
037
038 public class SocketInputStream extends FilterInputStream
039 {
040 private Socket __socket;
041
042 /***
043 * Creates a SocketInputStream instance wrapping an input stream and
044 * storing a reference to a socket that should be closed on closing
045 * the stream.
046 * <p>
047 * @param socket The socket to close on closing the stream.
048 * @param stream The input stream to wrap.
049 ***/
050 public SocketInputStream(Socket socket, InputStream stream)
051 {
052 super(stream);
053 __socket = socket;
054 }
055
056 /***
057 * Closes the stream and immediately afterward closes the referenced
058 * socket.
059 * <p>
060 * @exception IOException If there is an error in closing the stream
061 * or socket.
062 ***/
063 @Override
064 public void close() throws IOException
065 {
066 super.close();
067 __socket.close();
068 }
069 }