Ajout de TCPClient qui avait été oublié

This commit is contained in:
Marino Benassai 2020-11-26 09:58:27 +01:00
parent fae7931a77
commit 07af16987f

View file

@ -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();
}
}