5 public class SocketClient
{
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
10 public SocketClient() {
11 // établie une connexion au serveur par un appel
12 // à connexionServeur()
13 connexionServeur("localhost", 5000);
16 public SocketClient(String adresseIPServeur
, int portServeur
) {
17 // établie une connexion au serveur par un appel
18 // à connexionServeur()
19 connexionServeur(adresseIPServeur
, portServeur
);
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
27 sock
= new Socket(adresseIPServeur
, portServeur
);
29 catch (IOException e
) {
30 System
.err
.println("IOException: " + e
);
32 InputStream IStream
= null;
34 IStream
= sock
.getInputStream();
36 catch (IOException e
) {
37 System
.err
.println("IOException: " + e
);
39 InputStreamReader IMesg
= new InputStreamReader(IStream
);
40 lecture
= new BufferedReader(IMesg
);
42 OutputStream OStream
= null;
44 OStream
= sock
.getOutputStream();
46 catch (IOException e
) {
47 System
.err
.println("IOException: " + e
);
49 ecriture
= new PrintWriter(OStream
);
53 * Send a message on the opened client socket
54 * @param msg a string containing the message to send
56 public synchronized void sendMsg(String msg
) {
57 while (msg
.isEmpty()) {
61 catch (InterruptedException e
) {
62 System
.err
.println("InterruptedException: " + e
);
65 ecriture
.println(msg
);
71 * Receive a message sent on the opened client socket
72 * @return a string containing the received message
74 public String
receiveMsg() {
75 String line
= new String();
77 //FIXME: read only the line before the ending newline
78 line
= lecture
.readLine();
80 catch (IOException e
) {
81 System
.err
.println("IOException: " + e
);
87 * Close all opened I/O streams attached to this object instance
89 public void closeRWIO() {
94 catch (IOException e
) {
95 System
.err
.println("IOException: " + e
);
99 } // fin classe SocketClient