package it.unimi.dsi.mg4j.index.remote;
/*
* MG4J: Managing Gigabytes for Java
*
* Copyright (C) 2006-2010 Sebastiano Vigna
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
import it.unimi.dsi.fastutil.io.FastBufferedInputStream;
import it.unimi.dsi.fastutil.io.FastBufferedOutputStream;
import it.unimi.dsi.Util;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import org.apache.log4j.Logger;
/** An index server connection.
*
* <p>Instances of this class provide a convenient way to gather all fields
* related to a server connection (streams, socket, etc.).
*
* @author Alessandro Arrabito
* @author Sebastiano Vigna
*/
public class RemoteIndexServerConnection implements Closeable {
private static final Logger LOGGER = Util.getLogger( RemoteIndexServerConnection.class );
public final Socket socket;
/** The stream from the server. */
public final DataInputStream inputStream;
/** The stream towards the server. */
public final DataOutputStream outputStream;
/** Creates a remote index-server connection from a given address and command.
*
* <P>Immediately after establishing the connection, <code>command</code> is sent
* to the server, so the stream will be connected to a thread providing a specific service. See {@link IndexServer}.
*
* @param address the server address.
* @param command the first command sent to the server ({@link IndexServer#GET_CLIENT_INPUT_STREAM},
* {@link IndexServer#GET_INDEX_READER}, …).
*/
public RemoteIndexServerConnection( final SocketAddress address, final byte command ) throws IOException {
socket = new Socket();
socket.connect( address );
inputStream = new DataInputStream( new FastBufferedInputStream( socket.getInputStream() ) );
outputStream = new DataOutputStream( new FastBufferedOutputStream( socket.getOutputStream() ) );
outputStream.writeByte( command );
outputStream.flush();
}
/** Closes the underlying socket. */
public synchronized void close() throws IOException {
socket.close();
}
protected void finalize() throws Throwable {
try {
if ( ! socket.isClosed() ) {
LOGGER.warn( "This " + this.getClass().getName() + " [" + toString() + "] should have been closed." );
close();
}
}
finally {
super.finalize();
}
}
public String toString() {
return this.getClass().getName() + ":" + socket.toString();
}
}