2
1
Ответвление 0
Projet_POO/Projet_POO/src/reseau/TCPClient.java

123 строки
2,8 КиБ
Java
Исходный Авторство История

package reseau;
import java.net.*;
import java.io.*;
public class TCPClient {
InetAddress adresseCible = null;
InetAddress adresseSource = null;
int port = 0;
Socket socket = null;
BufferedReader input = null;
PrintWriter output = null;
public TCPClient() {
this.port = 0;
this.socket = null;
this.input = null;
this.output = null;
}
public TCPClient(String host, int port) {
this.port = port;
try {
this.socket = new Socket(host, port);
}
catch (UnknownHostException e) {
System.out.print("Could not find host\n");
}
catch (IOException e) {
System.out.print("Could not create socket\n");
}
this.adresseCible = socket.getInetAddress();
this.adresseSource = socket.getLocalAddress();
try {
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (IOException e) {
System.out.print("Error while reading input stream\n");
}
try {
this.output = new PrintWriter(socket.getOutputStream(),true);
}
catch (IOException e) {
System.out.print("Error while reading output stream\n");
}
}
public TCPClient(Socket socket) {
this.port = socket.getPort();
this.socket = socket;
this.adresseCible = socket.getInetAddress();
this.adresseSource = socket.getLocalAddress();
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() throws IOException{
String message = null;
message = input.readLine();
return message;
}
public void stop() {
try {
this.socket.close();
}
catch (IOException e) {
System.out.print("Error while closing connection\n");
}
}
public void changePort(int port) throws IOException {
this.stop();
this.port = port;
try {
this.socket = new Socket(this.adresseCible.getHostName(), port);
}
catch (UnknownHostException e) {
System.out.print("Could not find host");
}
}
public String getHostSource() {
return this.adresseSource.getHostName();
}
public String getAdresseSource() {
return this.adresseSource.getHostAddress();
}
public String getAdresseCible() {
return this.adresseCible.getHostAddress();
}
public static void main(String[] args) throws IOException{
TCPClient client = new TCPClient("localhost", 1999);
String message = "Bonjour.\n";
System.out.printf("Message envoy<6F>: %s", message);
client.send(message);
System.out.printf("Message re<72>u: %s\n", client.receive());
client.stop();
}
}