package rpn;

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



class ServerConnection {
	protected Socket serverConn;
	InputStream in;
	OutputStream out;
	
	public ServerConnection(String host, int port) 
		throws IOException, UnknownHostException {
		
		try {
			System.out.println("Trying " + host + " " + port);
			serverConn = new Socket(host, port);
		} catch(UnknownHostException e) {
			System.out.println("Submittor: " + e);
			throw new UnknownHostException();
		}
		catch (IOException e) {
			System.out.println("Submittor: " + e);
			throw new IOException();
		}
		try {
			out = serverConn.getOutputStream();
		} catch (IOException e) {
			System.out.println("Submittor: " + e);
			throw new IOException();
		}
		try {
			in = serverConn.getInputStream();
		} catch (IOException e) {
			System.out.println("Submittor: " + e);
			throw new IOException();
		}
		System.out.println("Connection established!");
	}
	
	public synchronized void finalize() throws IOException {
		System.out.println("Connection: closing!");
		serverConn.close();
	}
	
	void write(byte b) throws IOException {
		out.write(b);
	}
	
	void write(String s) throws IOException {
		System.out.println("Writing " + s);
		for (int i=0;i<s.length();i++) {
			out.write(s.charAt(i));
		} 
	}
	
	public int read() throws IOException {
		return(in.read());
	} 
}
