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