TD2: code cleanup in the client part.
[TD_SR.git] / TD2 / client / ClientSimplifie.java
CommitLineData
f734b987
JB
1import java.io.*;
2import java.net.*;
3import java.util.*;
4
5public class ClientSimplifie {
6 BufferedReader lecture; // pour le flot d'entrée venant du serveur
7 PrintWriter ecriture; // pour le flot de sortie vers le serveur
8 Socket sock; // le socket client
9
10 public ClientSimplifie() {
11 // établie une connexion au serveur par un appel
12 // à connexionServeur()
13 connexionServeur("localhost", 5000);
14 }
15
16 public ClientSimplifie(String adresseIPServeur, int portServeur) {
17 // établie une connexion au serveur par un appel
18 // à connexionServeur()
19 connexionServeur(adresseIPServeur, portServeur);
20 }
21
22 private void connexionServeur(String adresseIPServeur, int portServeur) {
23 // créer un objet socket lié au socket serveur et l'affecte à sock
24 // puis établie les chaînages de flot nécessaires
25 // pour l'envoi et la reception de messages
26 try {
27 sock = new Socket(adresseIPServeur, portServeur);
28 }
7293fe6d 29 catch (IOException e) {
ce28a021 30 System.err.println("IOException: " + e);
7293fe6d 31 }
f734b987
JB
32 InputStream IStream = null;
33 try {
34 IStream = sock.getInputStream();
367e2930 35 }
7293fe6d 36 catch (IOException e) {
ce28a021 37 System.err.println("IOException: " + e);
7293fe6d 38 }
f734b987
JB
39 InputStreamReader IMesg = new InputStreamReader(IStream);
40 lecture = new BufferedReader(IMesg);
41
42 OutputStream OStream = null;
43 try {
44 OStream = sock.getOutputStream();
45 }
7293fe6d 46 catch (IOException e) {
ce28a021 47 System.err.println("IOException: " + e);
7293fe6d 48 }
f734b987
JB
49 ecriture = new PrintWriter(OStream);
50 }
51
7293fe6d
JB
52 /**
53 * Send a message on the opened client socket
54 * @param msg a string containing the message to send
55 */
f734b987 56 public void sendMsg(String msg) {
4ab67210 57 ecriture.println(msg);
f734b987
JB
58 ecriture.flush();
59 }
60
7293fe6d
JB
61 /**
62 * Receive a message sent on the opened client socket
63 * @return a string containing the received message
64 */
f734b987
JB
65 public String receiveMsg() {
66 String line = new String();
67 try {
68 //FIXME: read only the line before the ending newline
69 line = lecture.readLine();
70 }
7293fe6d 71 catch (IOException e) {
ce28a021 72 System.err.println("IOException: " + e);
7293fe6d 73 }
f734b987
JB
74 return line;
75 }
76
7293fe6d
JB
77 /**
78 * Close all opened I/O streams attached to this object instance
79 */
f734b987
JB
80 public void closeRWIO() {
81 ecriture.close();
367e2930
JB
82 try {
83 lecture.close();
84 }
7293fe6d 85 catch (IOException e) {
ce28a021 86 System.err.println("IOException: " + e);
7293fe6d 87 }
f734b987
JB
88 }
89
90} // fin classe ClientSimplifie