1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
import java.io.*;
import java.net.*;
import java.util.Date;
public class Client {
static final int port = 8888;
static BufferedReader plec;
static PrintWriter pred;
static Socket socket;
static String strReponse = "";
public static void main(String[] args) throws Exception {
try
{
System.out.println("Début de traitement");
// Connexion au serveur
P_Login();
// Envoi de 10 records
//for (int i = 0; i < 2; i++)
P_SendOneRecord();
// Logout
P_Logout(false);
System.out.println("Fin de traitement");
}catch (Exception e) {
if (socket != null) P_Logout(true);
e.printStackTrace();
}
}
public static void P_Login() throws Exception{
// Connexion au serveur
socket = new Socket("192.168.1.18", port);
System.out.println("SOCKET créé : " + socket);
// Création des canaux de communication
plec = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pred = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
}
public static void P_SendOneRecord() throws Exception{
String str = sendMessage("Data", true);
if (!str.equals("ok")) P_Error(1);
}
public static void P_Error(int intCodeError) throws Exception{
System.out.println("Erreur à traiter");
switch (intCodeError)
{
case 1: throw new SendOneRecordException();
default: throw new Exception();
}
}
public static String sendMessage(String strMessage, boolean booResponse) throws Exception{
System.out.println("Envoi du message : " + strMessage);
pred.println(strMessage);
if (booResponse) strReponse = plec.readLine();
System.out.println("Réception réponse : " + strReponse);
return strReponse;
}
public static void P_Logout(boolean booException) throws Exception{
// Déconnexion au serveur
plec.close();
pred.close();
socket.close();
}
} |
Partager