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
9 ObjectOutput oEcriture
;
10 Socket sock
; // le socket client
12 public SocketClient() {
13 // établie une connexion au serveur par un appel
14 // à connexionServeur()
17 connexionServeur("localhost", 5000);
19 catch (IOException e
) {
20 System
.err
.println("IOException: " + e
);
26 public SocketClient(String adresseIPServeur
, int portServeur
) {
27 // établie une connexion au serveur par un appel
28 // à connexionServeur()
31 connexionServeur(adresseIPServeur
, portServeur
);
33 catch (IOException e
) {
34 System
.err
.println("IOException: " + e
);
40 private void connexionServeur(String adresseIPServeur
, int portServeur
, boolean hasoStream
) throws IOException
{
41 // créer un objet socket lié au socket serveur et l'affecte à sock
42 // puis établie les chaînages de flot nécessaires
43 // pour l'envoi et la reception de messages
44 sock
= new Socket(adresseIPServeur
, portServeur
);
46 OutputStream OStream
= sock
.getOutputStream();
47 ecriture
= new PrintWriter(OStream
);
49 oEcriture
= new ObjectOutputStream(OStream
);
51 InputStream IStream
= sock
.getInputStream();
52 InputStreamReader IMesg
= new InputStreamReader(IStream
);
53 lecture
= new BufferedReader(IMesg
);
55 oLecture
= new ObjectInputStream(IStream
);
58 private void connexionServeur(String adresseIPServeur
, int portServeur
) throws IOException
{
59 // créer un objet socket lié au socket serveur et l'affecte à sock
60 // puis établie les chaînages de flot nécessaires
61 // pour l'envoi et la reception de messages
62 connexionServeur(adresseIPServeur
, portServeur
, false);
65 private void attributesInit() {
74 * Send a message on the opened client socket
75 * @param msg a string containing the message to send
77 public void sendMsg(String msg
) {
78 ecriture
.println(msg
);
83 * Send an object message on the opened client socket
84 * @param msg a string containing the message to send
86 public void sendoMsg(Message oMsg
) throws IOException
{
87 oEcriture
.writeObject(oMsg
);
92 * Receive a message sent on the opened client socket
93 * @return a string containing the received message
95 public String
receiveMsg() throws IOException
{
96 String line
= new String();
97 //FIXME?: read only the line before the ending newline
98 line
= lecture
.readLine();
103 * Receive an object message sent on the opened client socket
104 * @return a string containing the received message
106 public Message
receiveoMsg() throws IOException
, ClassNotFoundException
{
107 return (Message
)oLecture
.readObject();
111 * Close all opened I/O streams attached to this object instance
113 public void closeRWIO() {
119 if (ecriture
!= null)
121 if (oLecture
!= null)
123 if (oEcriture
!= null) {
127 catch (IOException e
) {
128 System
.err
.println("IOException: " + e
);
133 } // fin classe SocketClient