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