From 07af16987f0fdf317b9cd5f294be531f1e0628d2 Mon Sep 17 00:00:00 2001 From: benassai Date: Thu, 26 Nov 2020 09:58:27 +0100 Subject: [PATCH] =?UTF-8?q?Ajout=20de=20TCPClient=20qui=20avait=20=C3=A9t?= =?UTF-8?q?=C3=A9=20oubli=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Projet_POO/src/reseau/TCPClient.java | 94 ++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Projet_POO/src/reseau/TCPClient.java 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(); + } +}