clase Cliente
public class Client extends javax.swing.JFrame{
private Socket client = null;
private String hostName;
private int port;
private BufferedReader entree;
private PrintWriter sortie;
private javax.swing.JButton boutonQuiter;
private javax.swing.JButton boutonConnexion;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel6;
private java.awt.Label label4;
private java.awt.Label label5;
private java.awt.TextArea textClient;
private java.awt.TextArea textServer;
private java.awt.TextField textField2; //adresse IP du server où on veut se connecter
private java.awt.TextField textField4; //port pour la communication
/** Le constructeur qui indique sur quel serveur se connecter et quel port solliciter
* il prend plus de paramètre, il s'initialise en prennant les infos fournies
* sur l'interface directement
* @throws IOException si erreur de connexion
*/
public Client() throws IOException {
initComponents();
setTimer();
setVisible(true);
setTitle("Client");
}
private void setTimer(){ //méthode pour afficher l'heure
javax.swing.Timer labelTimer;
DateFormat formatData=DateFormat.getTimeInstance(DateFormat.MEDIUM);
labelTimer=new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e){
jLabel1.setText(formatData.format(new Date()));
}
});
labelTimer.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel(); //horloge
jLabel2 = new javax.swing.JLabel(); //label Client
jLabel3 = new javax.swing.JLabel(); //label Port
textField2 = new java.awt.TextField();
textField4 = new java.awt.TextField();
jPanel2 = new javax.swing.JPanel();
boutonQuiter = new javax.swing.JButton();
boutonConnexion = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
textClient = new java.awt.TextArea();
textServer = new java.awt.TextArea();
label4 = new java.awt.Label();
label5 = new java.awt.Label();
jPanel6 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel2.setText("Client");
jLabel3.setText("Port");
textField2.setText("localhost");
textField4.setText("2222");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(117, 117, 117)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textField2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(37, 37, 37))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(22, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
boutonQuiter.setText("QUITTER");
boutonQuiter.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
boutonQuiterMouseClicked(evt);
}
});
boutonConnexion.setText("CONNEXION");
boutonConnexion.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {
boutonConnexionMouseClicked(evt);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(boutonQuiter)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(boutonConnexion)
.addGap(60, 60, 60))
);
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(boutonQuiter)
.addComponent(boutonConnexion))
.addContainerGap())
);
label4.setText("Client");
label5.setText("Serveur");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(textClient, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 300, Short.MAX_VALUE)
.addComponent(textServer, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(64, 64, 64))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(textServer, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
.addComponent(textClient, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE))
.addContainerGap())
);
jLabel1.setText("HELLO");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(173, 173, 173)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 12, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
//bouton affiche Connexion si y a pas de client, sinon si client exite il affiche envoyer
private void boutonConnexionMouseClicked(java.awt.event.MouseEvent evt) throws IOException{
if(client==null){
try {
// Convertir la chaine de caractères "hostName" en une adresse IP valide du serveur
hostName=textField2.getText(); //on récupère l'@ spécifiée
port=Integer.parseInt(textField4.getText());
InetAddress adresseIP = InetAddress.getByName(hostName);
//creer le Socket vers le serveur
client = new Socket(adresseIP, port);
appendServer("Nouveau client= "+client);
//on fixe un timeOut
client.setSoTimeout(1000);// 1s
}
catch(UnknownHostException e){
System.err.println("Je ne connais pas le serveur: "+hostName);
appendServer("Je ne connais pas le serveur: "+hostName);
throw e;
}
catch(SocketException e){
System.err.println("erreur de connexion ou timeout");
appendServer("erreur de connexion ou timeout");
throw e;
}
catch (IOException e) {
System.err.println("Probleme de connexion sur:"+hostName);
appendServer("Probleme de connexion sur:"+hostName);
throw e;
}
System.out.println("Connexion OK sur "+hostName);
appendServer("Connexion OK sur "+hostName);
try {
entree = new BufferedReader(new InputStreamReader(client.getInputStream() ) );
sortie = new PrintWriter(client.getOutputStream() );
}
catch (IOException e) {
System.err.println("PB creation des streams");
appendServer("PB creation des streams");
System.exit(1);
}
boutonConnexion.setText("ENVOYER");
}
}
/**
*
* @return socket client
*/
public Socket getSocket(){
return client;
}
/**
*
* @param chaine :message du serveur à ajouter au textServer
*/
public void appendServer(String chaine){
textServer.append(chaine+"\n");
}
/** lit les caracteres envoyés par le serveur.
* @return un objet String qui contient l'ensemble des caractères lus
*/
public String lireServeur(){
String ligne=null;
try{
ligne = entree.readLine();
}
catch (IOException e) {
System.err.println("rien a lire");
}
return ligne;
}
/** Envoie des données au serveur.
* @param ligne les caractères à envoyer
*/
public void ecrireServeur(String ligne){
sortie.println(ligne);
sortie.flush();
}
/** teste la connexion.
*@return un booléen notifiant l'état de la connexion
*/
public boolean estConnect(){
return client.isConnected();
}
/** Fermeture du socket.
*/
public void fermer(){
try{
entree.close();
sortie.close();
if (client != null){
client.close();
System.out.println ("Fermeture ok");
}
}
catch(IOException e){
System.err.println("Erreur à la fermeture des flux!");
}
}
/**Appel de la methode fermer()
*/
@Override
protected void finalize(){
fermer();
}
public void communiquer() {
// Que dit le serveur ?
String ligne = lireServeur();
System.out.println("Serveur : "+ligne);
appendServer("Serveur : "+ligne);
//Requete au serveur a partir de la console
System.out.print("Entree : ");
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String entree;
try{
while ((entree = console.readLine()) != null) {
ecrireServeur(entree);
ligne = lireServeur();
if (ligne != null) {
System.out.println("Serveur : "+ligne);// pour voir
if (ligne.equals("Au revoir"))
break;
}
System.out.print("Entree : ");
}
console.close();
}
catch(IOException e){
System.err.println("Erreur de lecture console");
}
}
}
Clase ClienteTest
public class MonClientTest{
Client mc=null; //initialisation de la variable locale
try{
mc = new Client();
System.out.println("mc = "+mc+ "client:"+mc.getSocket());
}
catch(IOException e) {
System.err.println("erreur de realisation du client"+mc);
if (mc != null){
mc.fermer();
mc = null; //on perd l'objet
}
}
if (mc != null) {
mc.communiquer();
mc.fermer();
}
else
System.err.println("Impossible de créer le client, mc ==null !!");
}
}