Newer
Older
nonet / src / ch / epfl / lca / sc250 / TCPClient.java
@Andreas Jaggi Andreas Jaggi on 17 May 2006 2 KB Finished TP7, started work on TP8
package ch.epfl.lca.sc250;

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

import ch.epfl.lca.sc250.gui.*;

public class TCPClient {

	private Socket sock;

	private String targethost;

	private int targetport;

	private String name;

	private	BufferedReader inr;
	private	DataOutputStream outs;

	private CnFrameTCP gui;


	public static void main ( String[] args ) {

			TCPClient tc = new TCPClient("in3sun23.epfl.ch", 13370, "x-way");
			tc.join();
			tc.loop();
			tc.leave();
	}

	void loop ( ) {

		boolean finished = false;

		BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

		while ( !finished ) {

			try {
				String cmd = consoleReader.readLine();

				if ( cmd.trim().equals("Bye Bye") ) {
					finished = true;
				}

				write(cmd);
				gui.appendText(cmd);
				gui.appendText(read());
			} catch ( IOException e ) {
				System.err.println("IOError");
				gui.appendText("IO-Error");
				e.printStackTrace();
			}
		}
	}

	TCPClient ( String targethost, int targetport, String name ) {
		gui = new CnFrameTCP("TCPClient");
		this.targethost = targethost;
		this.targetport = targetport;
		this.name = name;

		try {
			sock = new Socket(targethost, targetport);
		} catch ( UnknownHostException uhe ) {
			System.out.println("Unknown host");
			gui.appendText("Unknown host");
			uhe.printStackTrace();
		} catch ( IOException e ) {
			System.err.println("IOError");
			gui.appendText("IO-Error");
			e.printStackTrace();
		}

		try {
			outs = new DataOutputStream(sock.getOutputStream());
			inr = new BufferedReader(new InputStreamReader(sock.getInputStream()));
		} catch ( IOException e ) {
			System.err.println("IOError");
			gui.appendText("IO-Error");
			e.printStackTrace();
		}
	}

	public void join ( ) {
		write("Hello: " + name + "\n");
		String t = read();
		System.out.println(t);
		gui.appendText(t);
	}

	public void leave ( ) {
		try {
			sock.close();
		} catch ( IOException e ) {
			System.err.println("IOError");
			gui.appendText("IO-Error");
			e.printStackTrace();
		}
		System.out.println("Connection closed.");
		gui.appendText("Connection closed.");
	}

	public void write ( String s ) {
		try {
			outs.writeBytes(s);
		} catch ( IOException e ) {
			System.err.println("IOError");
			gui.appendText("IO-Error");
			e.printStackTrace();
		}
	}

	public String read ( ) {
		try {
			return inr.readLine();
		} catch ( IOException e ) {
			System.err.println("IOError");
			gui.appendText("IO-Error");
			e.printStackTrace();
			return "";
		}
	}
}