package ch.epfl.lca.sc250; import java.net.*; import java.io.*; import ch.epfl.lca.sc250.gui.finalgui.*; public class TCPClient extends Thread { private Socket sock; private String targethost; private int targetport; private String name; private BufferedReader inr; private DataOutputStream outs; private CnFrameMain gui; public static void main ( String[] args ) { TCPClient tc = new TCPClient("in3sun23.epfl.ch", 13370, "x-way", new CnFrameMain("abc")); tc.init(); tc.joinGame(); tc.loop(); tc.leave(); } public void run ( ) { this.init(); this.joinGame(); this.loop(); this.leave(); } public 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, CnFrameMain gui ) { this.gui = gui; this.targethost = targethost; this.targetport = targetport; this.name = name; } public void init ( ) { 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 joinGame ( ) { 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 ""; } } }