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

public class Wind2TCPLink extends Wind2Link
{
	protected Socket s = null;
	protected BufferedReader i = null;
	protected PrintWriter o = null;

	protected String host;
	protected int port;

	public Wind2TCPLink (IniFile ini) {
		host = ini.getValue("TCP", "host");
		port = new Integer(ini.getValue("TCP", "port")).intValue();
	}
		
	public boolean Connect()
	{
		try {
			s = new Socket(host, port);
			o = new PrintWriter(s.getOutputStream(),
					true);
			i = new BufferedReader(new InputStreamReader(
						s.getInputStream()));
		} catch (UnknownHostException e) {
			System.out.println("Unknown Host: " + e);
			return false;
		} catch (IOException e) {
			System.out.println("No I/O: " + e);
			Disconnect();
			return false;
		}
		return true;
	}
	
	public String getLine()
	{
		String line = null;
		try {
			line = i.readLine();
		} catch (IOException e) {
			System.out.println("Read failed: " + e);
			return null;
		}
		return line;
	}
	
	public boolean Disconnect()
	{
		if (i != null) {
			try {
				i.close();
			} catch (IOException e) {
				System.err.println("Error closing: " + e);
			}
			i = null;
		}
		if (o != null) {
			o.close();
			o = null;
		}
		if (s != null) {
			try {
				s.close();
			} catch (IOException e) {
				System.err.println("Error closing: " + e);
			}
			s = null;
		}

		return true;
	}

	public static void main (String args[])
	{
		Wind2Link l = new Wind2TCPLink(new IniFile(args[0]));

		System.out.println("Connecting...");
		l.Connect();
		System.out.println("Connected.");

		System.out.println("Reading...");
		String line = null;
		while ((line = l.getLine()) != null)
			System.out.println(line);
		System.out.println("Done.");

		l.Disconnect();
	}
}
