diff --git a/Projet_POO/src/reseau/TCPClient.java b/Projet_POO/src/reseau/TCPClient.java new file mode 100644 index 0000000..41f4b19 --- /dev/null +++ b/Projet_POO/src/reseau/TCPClient.java @@ -0,0 +1,94 @@ +package reseau; +import java.net.*; +import java.io.*; + +public class TCPClient { + String host = null; + int port = 0; + Socket socket = null; + BufferedReader input = null; + PrintWriter output = null; + + public TCPClient() { + this.host = null; + this.port = 0; + this.socket = null; + this.input = null; + this.output = null; + } + + public TCPClient(String host, int port) { + this.host = host; + this.port = port; + try { + this.socket = new Socket(host, port); + } + catch (UnknownHostException e) { + System.out.print("Could not find host"); + } + catch (IOException e) { + System.out.print("Could not create socket"); + } + try { + this.input = new BufferedReader(new InputStreamReader(socket.getInputStream())); + } + catch (IOException e) { + System.out.print("Error while reading input stream"); + } + try { + this.output = new PrintWriter(socket.getOutputStream(),true); + } + catch (IOException e) { + System.out.print("Error while reading output stream"); + } + + } + + public void send(String message) { + //Le message doit se terminer par \n ? + this.output.print(message); + this.output.flush(); + } + + public String receive() { + String message = null; + try { + message = input.readLine(); + } + catch (IOException e) { + System.out.print("Error while reading buffer"); + } + return message; + } + + public void stop() { + try { + this.socket.close(); + } + catch (IOException e) { + System.out.print("Error while closing connection"); + } + + + } + + public void changePort(int port) throws IOException { + this.stop(); + this.port = port; + try { + this.socket = new Socket(host, port); + } + catch (UnknownHostException e) { + System.out.print("Could not find host"); + } + } + + public static void main(String[] args) { + TCPClient client = new TCPClient("localhost", 1999); + String message = "Bonjour.\n"; + System.out.printf("Message envoyé: %s", message); + client.send(message); + System.out.printf("Message reçu: %s\n", client.receive()); + client.stop(); + } +}