import java.io.*;
import java.net.*;

public class Connection {
	private BufferedReader in = null;
	private PrintWriter out = null;
	
	private Socket socket = null;
	
	public Connection( Socket s ) throws IOException {
		refresh( s );
	}
	
	public void refresh( Socket s ) throws IOException {
		if (socket != null) {
			close();
		}
		
		try {
			socket = s;
			in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
			out = new PrintWriter( socket.getOutputStream(), true );
		} catch (IOException e) {
			socket = null;
			in = null;
			out = null;
			throw new IOException( "Could not initiate connection.", e );
		}
	}

	public void send( String s ) {
		if (out != null) {
			out.print( s );
			out.flush();
		}
	}
	
	public void sendln( String s ) {
		if (out != null) {
			out.println( s );
		}
	}
	
	public String readln() throws IOException {
		if (in == null) {
			throw new IOException( "Could not read string." );
		}
		
		return in.readLine();
	}
	
	public void close() {
		if (!(socket == null || socket.isClosed())) {
			try {
				socket.close();
			} catch (IOException e) {
				// ??! Not so sure what kind of I/O error (that I care about) could occur trying to close a
				//  Socket... Either way, do nothing for now (until someone can enlighten me).
			} finally {
				socket = null;
			}
		}
	}
}
