0% found this document useful (0 votes)
4 views

Code Complet(Java _ Python _ Scala)

Cours

Uploaded by

leye.maguette1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Code Complet(Java _ Python _ Scala)

Cours

Uploaded by

leye.maguette1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Code Serveur Java

mardi 3 décembre 2024 21:01

package Quiz_Package;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.table.DefaultTableModel;
import java.util.Arrays;
import java.util.List;

public class ClientQuiz extends javax.swing.JFrame {

private static final String SERVER_ADDRESS = "localhost"; // Adresse du serveur


private static final int SERVER_PORT = 12345; // Port du serveur
private Socket socket;
private PrintWriter out;
private BufferedReader in;

private List<String> questions = null; // Liste des questions


private int currentQuestionIndex = 0; // Index de la question actuelle
private boolean connected = false; // Indique si le client est connecté

/**
* Creates new form ClientQuiz
*/
public ClientQuiz() {
initComponents();
// Initialisation des questions
questions = Arrays.asList(
"Q1. Une @ IPV6 tient sur :\n A. 32 bits\n B. 128 bits",
"Q2. Un numéro de port sert à : A. Identifier une machine B. Identifier une application",
"Q3. L'API Socket est au niveau : A. Transport B. Application",
"Q4. TCP fonctionne en mode : \n A. Connecté\n B. Non connecté",
"Q5. UDP est :\n A. Fiable\n B. Non Fiable ",
"Q6. 10.0.0.1 est une @ IPV4 :\n A. Privée\n B. Public ",
"Q7. 197.0.0.1 est une @ IPV4 :\n A. Classe D\n B. Classe C ",
"Q8. ServerSocket est la classe Java qui implémente :\n A. Les Sockets d’écoute\n B. Les Sockets de transfert",
"Q9. La classe Date est définie dans :\n A. Java.io\n B. Java.util ",
"Q10. La classe InetAddress correspond à :\n A. Adresse IP\n B. Adresse URL"
);

// Afficher la première question


afficherQuestion();
}
private void afficherQuestion() {
if (currentQuestionIndex < questions.size()) {
// Afficher la question actuelle dans jTextArea1
jTextArea1.setText(questions.get(currentQuestionIndex));
} else {
jTextArea1.setText("Fin des questions. Cliquez sur 'Quitter'.");
}
}
private void connectToServer() {
try {
socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Afficher les questions dans jTextArea1


String question;
while ((question = in.readLine()) != null) {
jTextArea1.append(question + "\n");
}

Code Complet(Java _ Python _ Scala) Page 1


}
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendAnswer() {
if (!connected) {
jTextArea1.setText("Veuillez d'abord vous connecter au serveur.");
return;
}
while (currentQuestionIndex < questions.size()) {
// Vérifier si une réponse a été saisie
String reponse = jTextField1.getText().trim();
if (reponse.isEmpty()) {
jTextArea1.setText("Veuillez saisir une réponse avant de continuer.");
return;
}

// Envoyer la réponse au serveur


out.println(reponse);
// Passer à la question suivante
currentQuestionIndex++;
afficherQuestion();

// Lire le score final si c'était la dernière question


if (currentQuestionIndex == questions.size()) {
try {
String score = in.readLine(); // Lire le score envoyé par le serveur
jTextField2.setText(score); // Afficher le score dans le champ texte
socket.close(); // Fermer la connexion au serveur
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 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() {

jLabel1 = new javax.swing.JLabel();


jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel3 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("Algerian", 3, 36)); // NOI18N


jLabel1.setForeground(new java.awt.Color(0, 102, 0));
jLabel1.setText("Client QUIZ");

jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jLabel2.setText("Question ?");

Code Complet(Java _ Python _ Scala) Page 2


jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jLabel3.setText("Ma Réponse");

jTextField1.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jTextField1.setForeground(new java.awt.Color(51, 102, 0));

jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jLabel4.setText("Mon Score");

jTextField2.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jTextField2.setForeground(new java.awt.Color(51, 102, 0));

jButton1.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jButton1.setText("Connecter");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jButton2.setText("Question Suivant");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jButton3.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jButton3.setText("Quitter");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(36, 36, 36)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jButton3))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(62, 62, 62)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)))))

Code Complet(Java _ Python _ Scala) Page 3


.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(10, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap(29, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
connectToServer(); // Se connecter au serveur

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
sendAnswer(); // Envoyer la réponse et passer à la question suivante

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
System.exit(0); // Quitter l'application

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}

Code Complet(Java _ Python _ Scala) Page 4


}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ClientQuiz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ClientQuiz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ClientQuiz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ClientQuiz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClientQuiz().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}

Code Complet(Java _ Python _ Scala) Page 5


Code Client Java
mardi 3 décembre 2024 21:04

package Quiz_Package;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.table.DefaultTableModel;
import java.util.Arrays;
import java.util.List;

public class ClientQuiz extends javax.swing.JFrame {

private static final String SERVER_ADDRESS = "localhost"; // Adresse du serveur


private static final int SERVER_PORT = 12345; // Port du serveur
private Socket socket;
private PrintWriter out;
private BufferedReader in;

private List<String> questions = null; // Liste des questions


private int currentQuestionIndex = 0; // Index de la question actuelle
private boolean connected = false; // Indique si le client est connecté

/**
* Creates new form ClientQuiz
*/
public ClientQuiz() {
initComponents();
// Initialisation des questions
questions = Arrays.asList(
"Q1. Une @ IPV6 tient sur :\n A. 32 bits\n B. 128 bits",
"Q2. Un numéro de port sert à : A. Identifier une machine B. Identifier une application",
"Q3. L'API Socket est au niveau : A. Transport B. Application",
"Q4. TCP fonctionne en mode : \n A. Connecté\n B. Non connecté",
"Q5. UDP est :\n A. Fiable\n B. Non Fiable ",
"Q6. 10.0.0.1 est une @ IPV4 :\n A. Privée\n B. Public ",
"Q7. 197.0.0.1 est une @ IPV4 :\n A. Classe D\n B. Classe C ",
"Q8. ServerSocket est la classe Java qui implémente :\n A. Les Sockets d’écoute\n B. Les Sockets de transfert",
"Q9. La classe Date est définie dans :\n A. Java.io\n B. Java.util ",
"Q10. La classe InetAddress correspond à :\n A. Adresse IP\n B. Adresse URL"
);

// Afficher la première question


afficherQuestion();
}
private void afficherQuestion() {
if (currentQuestionIndex < questions.size()) {
// Afficher la question actuelle dans jTextArea1
jTextArea1.setText(questions.get(currentQuestionIndex));
} else {
jTextArea1.setText("Fin des questions. Cliquez sur 'Quitter'.");
}
}
private void connectToServer() {
try {
socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Afficher les questions dans jTextArea1


String question;

Code Complet(Java _ Python _ Scala) Page 6


String question;
while ((question = in.readLine()) != null) {
jTextArea1.append(question + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendAnswer() {
if (!connected) {
jTextArea1.setText("Veuillez d'abord vous connecter au serveur.");
return;
}
while (currentQuestionIndex < questions.size()) {
// Vérifier si une réponse a été saisie
String reponse = jTextField1.getText().trim();
if (reponse.isEmpty()) {
jTextArea1.setText("Veuillez saisir une réponse avant de continuer.");
return;
}

// Envoyer la réponse au serveur


out.println(reponse);
// Passer à la question suivante
currentQuestionIndex++;
afficherQuestion();

// Lire le score final si c'était la dernière question


if (currentQuestionIndex == questions.size()) {
try {
String score = in.readLine(); // Lire le score envoyé par le serveur
jTextField2.setText(score); // Afficher le score dans le champ texte
socket.close(); // Fermer la connexion au serveur
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 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() {

jLabel1 = new javax.swing.JLabel();


jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel3 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

Code Complet(Java _ Python _ Scala) Page 7


jLabel1.setFont(new java.awt.Font("Algerian", 3, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 102, 0));
jLabel1.setText("Client QUIZ");

jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jLabel2.setText("Question ?");

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jLabel3.setText("Ma Réponse");

jTextField1.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jTextField1.setForeground(new java.awt.Color(51, 102, 0));

jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jLabel4.setText("Mon Score");

jTextField2.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jTextField2.setForeground(new java.awt.Color(51, 102, 0));

jButton1.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jButton1.setText("Connecter");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jButton2.setText("Question Suivant");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jButton3.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N


jButton3.setText("Quitter");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(36, 36, 36)
.addComponent(jButton2)

Code Complet(Java _ Python _ Scala) Page 8


.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 73,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(62, 62, 62)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 360,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(10, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap(29, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
connectToServer(); // Se connecter au serveur

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
sendAnswer(); // Envoyer la réponse et passer à la question suivante

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
System.exit(0); // Quitter l'application

Code Complet(Java _ Python _ Scala) Page 9


}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ClientQuiz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ClientQuiz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ClientQuiz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ClientQuiz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClientQuiz().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}

Code Complet(Java _ Python _ Scala) Page 10


Code Serveur Python
mardi 3 décembre 2024 21:06

import socket
import threading
import tkinter as tk
from tkinter import ttk
from datetime import datetime

class ServeurQuiz:
def __init__(self, root):
self.root = root
self.root.title("Serveur QUIZ")
self.root.geometry("400x300")

self.client_count = 0
self.correct_answers = ["B", "B", "A", "A", "B", "A", "B", "A", "B", "A"]

# Widgets
self.label_title = tk.Label(root, text="Serveur QUIZ", font=("Algerian", 24), fg="dark blue")
self.label_title.pack(pady=10)

self.label_date = tk.Label(root, text="Date d'aujourd'hui", font=("Segoe UI", 12))


self.label_date.pack()

self.date_text = tk.Entry(root, font=("Segoe UI", 12), fg="dark blue", state="readonly")


self.date_text.pack(pady=5)

# Buttons at the top


self.button_frame = tk.Frame(root)
self.button_frame.pack(pady=10)

self.start_button = tk.Button(self.button_frame, text="Démarrer Serveur", font=("Segoe UI", 12),


command=self.start_server)
self.start_button.pack(side="left", padx=10)

self.stop_button = tk.Button(self.button_frame, text="Fermer Serveur", font=("Segoe UI", 12),


command=self.stop_server)
self.stop_button.pack(side="right", padx=10)

# Table at the bottom


self.client_table = ttk.Treeview(root, columns=("N°Client", "Nom Thread", "Heure de connexion"),
show="headings", height=6)
self.client_table.heading("N°Client", text="N°Client")
self.client_table.heading("Nom Thread", text="Nom Thread")
self.client_table.heading("Heure de connexion", text="Heure de connexion")
self.client_table.pack(fill="both", padx=10, pady=10)

# Adjust the column width


self.client_table.column("N°Client", width=80, anchor="center")
self.client_table.column("Nom Thread", width=150, anchor="center")
self.client_table.column("Heure de connexion", width=150, anchor="center")

Code Complet(Java _ Python _ Scala) Page 11


self.update_date()

def update_date(self):
current_date = datetime.now().strftime("%a %b %d %Y")
self.date_text.config(state="normal")
self.date_text.delete(0, tk.END)
self.date_text.insert(0, current_date)
self.date_text.config(state="readonly")

def start_server(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind(('localhost', 50000))
self.server_socket.listen(5)
self.start_button.config(state="disabled")
threading.Thread(target=self.accept_clients).start()

def accept_clients(self):
while True:
client_socket, client_address = self.server_socket.accept()
self.client_count += 1
self.add_client_to_table(f"Client-{self.client_count}", f"Thread-{self.client_count}",
datetime.now().strftime("%H:%M:%S"))
threading.Thread(target=self.handle_client, args=(client_socket,)).start()

def add_client_to_table(self, client_number, thread_name, connection_time):


if len(self.client_table.get_children()) >= 4:
self.client_table.delete(self.client_table.get_children()[0]) # Supprimer la première ligne si on dépasse 4
clients
self.client_table.insert("", "end", values=(client_number, thread_name, connection_time))

def handle_client(self, client_socket):


score = 0
try:
for i, correct_answer in enumerate(self.correct_answers):
client_answer = client_socket.recv(1024).decode()
if client_answer.strip().upper() == correct_answer:
score += 1
client_socket.sendall(f"Votre score est : {score}".encode())
finally:
client_socket.close()

def stop_server(self):
if hasattr(self, 'server_socket'):
self.server_socket.close()
self.start_button.config(state="normal")
self.stop_button.config(state="disabled")

if __name__ == "__main__":
root = tk.Tk()
app = ServeurQuiz(root)
root.mainloop()

Code Complet(Java _ Python _ Scala) Page 12


Code Client Python
mardi 3 décembre 2024 21:06

import socket
import threading
import tkinter as tk
from tkinter import messagebox
from tkinter import scrolledtext

SERVER_ADDRESS = 'localhost'
SERVER_PORT = 50000

class ClientQuizApp:
def __init__(self, root):
self.root = root
self.root.title("Client QUIZ")
self.root.geometry("400x500")

self.socket = None
self.out = None
self.in_ = None
self.connected = False
self.questions = [
"Q1. Une @ IPV6 tient sur :\n A. 32 bits\n B. 128 bits",
"Q2. Un numéro de port sert à : A. Identifier une machine B. Identifier une application",
"Q3. L'API Socket est au niveau : A. Transport B. Application",
"Q4. TCP fonctionne en mode : \n A. Connecté\n B. Non connecté",
"Q5. UDP est :\n A. Fiable\n B. Non Fiable ",
"Q6. 10.0.0.1 est une @ IPV4 :\n A. Privée\n B. Public ",
"Q7. 197.0.0.1 est une @ IPV4 :\n A. Classe D\n B. Classe C ",
"Q8. ServerSocket est la classe Java qui implémente :\n A. Les Sockets d’écoute\n B. Les Sockets de transfert",
"Q9. La classe Date est définie dans :\n A. Java.io\n B. Java.util ",
"Q10. La classe InetAddress correspond à :\n A. Adresse IP\n B. Adresse URL"
]
self.current_question_index = 0

# Initialisation de l'interface graphique


self.init_ui()

def init_ui(self):
# Titre
self.label_title = tk.Label(self.root, text="Client QUIZ", font=("Algerian", 36), fg="green")
self.label_title.pack(pady=10)

# Affichage de la question
self.label_question = tk.Label(self.root, text="Question ?", font=("Segoe UI", 12))
self.label_question.pack()

self.text_area = scrolledtext.ScrolledText(self.root, width=40, height=5, wrap=tk.WORD, font=("Segoe UI", 12))


self.text_area.pack(pady=10)

# Frame pour les réponses et le score


frame_bottom = tk.Frame(self.root)
frame_bottom.pack(pady=10)

# Réponse de l'utilisateur
self.label_answer = tk.Label(frame_bottom, text="Ma Réponse", font=("Segoe UI", 12))
self.label_answer.grid(row=0, column=0, padx=10)

self.entry_answer = tk.Entry(frame_bottom, font=("Segoe UI", 12), fg="green", width=10) # Largeur réduite


self.entry_answer.grid(row=0, column=1, padx=10, ipadx=20)

Code Complet(Java _ Python _ Scala) Page 13


# Score
self.label_score = tk.Label(frame_bottom, text="Mon Score", font=("Segoe UI", 12))
self.label_score.grid(row=0, column=2, padx=10)

self.entry_score = tk.Entry(frame_bottom, font=("Segoe UI", 12), fg="green", state="readonly", width=10) # Largeur réduite
self.entry_score.grid(row=0, column=3, padx=10, ipadx=20)

# Frame pour les boutons


frame_buttons = tk.Frame(self.root)
frame_buttons.pack(pady=20)

self.button_connect = tk.Button(frame_buttons, text="Connecter", font=("Segoe UI", 12), command=self.connect_to_server)


self.button_connect.grid(row=0, column=0, padx=10)

self.button_next = tk.Button(frame_buttons, text="Question Suivante", font=("Segoe UI", 12), command=self.send_answer)


self.button_next.grid(row=0, column=1, padx=10)

self.button_exit = tk.Button(frame_buttons, text="Quitter", font=("Segoe UI", 12), command=self.exit_app)


self.button_exit.grid(row=0, column=2, padx=10)

def connect_to_server(self):
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((SERVER_ADDRESS, SERVER_PORT))
self.out = self.socket.makefile('w')
self.in_ = self.socket.makefile('r')

self.connected = True
self.text_area.delete(1.0, tk.END)
self.display_question()
except Exception as e:
messagebox.showerror("Erreur", f"Erreur de connexion: {str(e)}")

def display_question(self):
if self.current_question_index < len(self.questions):
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, self.questions[self.current_question_index])
else:
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, "Fin des questions. Cliquez sur 'Quitter'.")

def send_answer(self):
if not self.connected:
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, "Veuillez d'abord vous connecter au serveur.")
return

response = self.entry_answer.get().strip()
if not response:
messagebox.showwarning("Attention", "Veuillez saisir une réponse avant de continuer.")
return

self.out.write(response + "\n")
self.out.flush()
self.current_question_index += 1
self.display_question()

if self.current_question_index == len(self.questions):
score = self.in_.readline().strip()
self.entry_score.config(state="normal")
self.entry_score.delete(0, tk.END)
self.entry_score.insert(0, score)
self.entry_score.config(state="readonly")

Code Complet(Java _ Python _ Scala) Page 14


self.entry_score.config(state="readonly")
self.socket.close()
self.connected = False

def exit_app(self):
if self.socket:
self.socket.close()
self.root.quit()

if __name__ == "__main__":
root = tk.Tk()
app = ClientQuizApp(root)
root.mainloop()

Code Complet(Java _ Python _ Scala) Page 15


Code Serveur Scala
mardi 3 décembre 2024 21:07

importjavafx.application.{Application,Platform}
importjavafx.scene.Scene
importjavafx.scene.control.{Button,Label,TextArea,TextField}
importjavafx.scene.layout.{HBox,Pane,VBox}
importjavafx.stage.Stage

importscala.collection.mutable.ArrayBuffer
importjava.net.{ServerSocket,Socket}
importjava.io.{BufferedReader,InputStreamReader,PrintWriter}
importjava.time.LocalTime
importscala.concurrent.ExecutionContext.Implicits.global
importscala.concurrent.Future
importjavafx.collections.FXCollections
importjavafx.collections.ObservableList

objectserveurextendsApp{
Application.launch(classOf[MyServer])
}

//Classereprésentantunelignedutableau
caseclassClientInfo(clientNumber:Int,threadName:String,connectionTime:String)

classMyServerextendsApplication{
@volatilevarserverRunning=false
varclientCount=0//Compteurdeclients
valclientData:ObservableList[ClientInfo]=FXCollections.observableArrayList()//Donnéespourletableau

overridedefstart(primaryStage:Stage):Unit={
//Déclarationanticipéedesvariablesnécessaires
valtextArea=newTextArea()//Utilisationd'unTextAreapourafficherlesinformationsdesclients
textArea.setEditable(false)//RendreleTextAreanonéditable
textArea.setWrapText(true)//ActiverleretouràlalignedansleTextArea
textArea.setPrefSize(420,150)//FixerlatailleduTextArea
//Boutonspourdémarrer
valbutton1=newButton("DémarrerServeur")
button1.setLayoutX(10)
button1.setStyle("-fx-background-color:blue;-fx-text-fill:white;")
//Boutonspourarrêterleserveur
valbutton2=newButton("FermerServeur")
button2.setStyle("-fx-background-color:blue;-fx-text-fill:white;")

vallabel1=newLabel("ServeurQuiz")
label1.setStyle("-fx-font-size:36px;-fx-font-family:'Algerian';-fx-text-fill:blue;")
label1.setLayoutX(130)

vallabel2=newLabel("Dated'aujourd'hui:")
valtextField=newTextField(s"${java.time.LocalDate.now()}")
textField.setEditable(false)

valaligneTexte=newVBox(5,label2,textField)
valaligneButton=newHBox(230,button1,button2)

varserverSocket:Option[ServerSocket]=None
varclientSocket:Option[Socket]=None
varout:Option[PrintWriter]=None
varin:Option[BufferedReader]=None

Code Complet(Java _ Python _ Scala) Page 16


varin:Option[BufferedReader]=None
@volatilevari=0//Indexdelaquestionactuelle
valReponse=ArrayBuffer("B","B","A","A","B","A","B","A","B","A")

//Méthodepourarrêterleserveur
defstopServer():Unit=Future{
try{
serverRunning=false
in.foreach(_.close())
out.foreach(_.close())
clientSocket.foreach(_.close())
serverSocket.foreach(_.close())
i=0
in=None
out=None
clientSocket=None
serverSocket=None
println("Serveurarrêté.")
Platform.runLater(()=>println("Serveurprêtàredémarrer."))//Miseàjourasynchrone
}catch{
caseex:Exception=>
println(s"Erreurlorsdel'arrêtduserveur:${ex.getMessage}")
}
}

button1.setOnAction(_=>{
if(serverRunning){
println("Leserveurestdéjàencoursd'exécution.")
return
}

serverRunning=true
Future{
try{
serverSocket=Some(newServerSocket(12345))
println("Serveurdémarré,enattentedeconnexions...")

while(serverRunning){
valsocket=serverSocket.get.accept()//Accepteruneconnexionclient
clientCount+=1
valthreadName=s"Thread-$clientCount"
valconnectionTime=LocalTime.now().withNano(0).toString+"GMT"

//AjouterlesinformationsduclientdansleTextArea
Platform.runLater(()=>{
valclientInfo=ClientInfo(clientCount,threadName,connectionTime)
valclientInfoText=s"Client${clientInfo.clientNumber}|${clientInfo.threadName}|${clientInfo.connectionTime}"
valupdatedText=textArea.getText+"\n"+clientInfoText
textArea.setText(updatedText)//AjouterlesinformationsdeclientauTextArea
if(textArea.getText.split("\n").length>4){
//Limiterà4lignesdansleTextArea
vallines=textArea.getText.split("\n").drop(1).mkString("\n")
textArea.setText(lines)
}

println(s"Clientajouté:$clientData")
})

println(s"Client$clientCountconnecté!")
Future{
vallocalOut=newPrintWriter(socket.getOutputStream,true)
vallocalIn=newBufferedReader(newInputStreamReader(socket.getInputStream))

Code Complet(Java _ Python _ Scala) Page 17


vallocalIn=newBufferedReader(newInputStreamReader(socket.getInputStream))
varlocalIndex=0

try{
while(serverRunning){
valmessage=localIn.readLine()
if(message==null)thrownewException("Clientdéconnecté.")
valresponse=if(localIndex>9||message!=Reponse(localIndex))"false"else"true"
localOut.println(response)
localIndex+=1
}
}catch{
caseex:Exception=>
println(s"Erreurpourleclient$clientCount:${ex.getMessage}")
}finally{
localIn.close()
localOut.close()
socket.close()
}
}(scala.concurrent.ExecutionContext.global)
}
}catch{
caseex:Exception=>
println(s"Erreurduserveur:${ex.getMessage}")
}finally{
stopServer()
}
}
})
//Boutonpourfermerleserver
button2.setOnAction(_=>stopServer())

//ConfigurationduTextArea
textArea.setLayoutX(30)
textArea.setLayoutY(200)

valroot=newPane()
root.getChildren.addAll(label1,aligneTexte,aligneButton,textArea)

aligneTexte.setLayoutX(180)
aligneTexte.setLayoutY(80)
aligneButton.setLayoutX(30)
aligneButton.setLayoutY(150)

valscene=newScene(root,500,400)
primaryStage.setTitle("ServeurScalaavecJavaFX")
primaryStage.setScene(scene)
primaryStage.setResizable(false)
primaryStage.show()
}
}

Code Complet(Java _ Python _ Scala) Page 18


Code Client Scala
mardi 3 décembre 2024 21:08

importjavafx.application.{Application,Platform}
importjavafx.scene.Scene
importjavafx.scene.layout.{HBox,Pane}
importjavafx.scene.control.{Button,Label,TextArea,TextField}
importjavafx.stage.Stage
importscala.collection.mutable.ArrayBuffer
importjava.net.Socket
importjava.io.{BufferedReader,InputStreamReader,PrintWriter}

objectMainextendsApp{
Application.launch(classOf[client])
}

classclientextendsApplication{
overridedefstart(primaryStage:Stage):Unit={
//Questions
valQ1="Q1.Une@IPV6tientsur:\nA.32bits\nB.128bits"
valQ2="Q2.Unnumérodeportsertà:\nA.Identifierunemachine\nB.Identifieruneapplication"
valQ3="Q3.L’APISocketestauniveau:\nA.Transport\nB.Application"
valQ4="Q4.TCPfonctionneenmode\nA.Connecté\nB.Nonconnecté"
valQ5="Q5.UDPest:\nA.Fiable\nB.NonFiable"
valQ6="Q6.10.0.0.1estune@IPV4:\nA.Privée\nB.Public"
valQ7="Q7.197.0.0.1estune@IPV4:\nA.ClasseD\nB.ClasseC"
valQ8="Q8.ServerSocketestlaclasseJavaquiimplémente:\nA.LesSocketsd’écoute\nB.LesSocketsdetransfert"
valQ9="Q9.LaclasseDateestdéfiniedans:\nA.Java.io\nB.Java.util"
valQ10="Q10.LaclasseInetAddresscorrespondà:\nA.AdresseIP\nB.AdresseURL"
vars=0
//Déclarationdesvariablespartagées
varclientSocket:Option[Socket]=None//Serainitialisélorsquebutton1estcliqué
varout:Option[PrintWriter]=None//Fluxdesortie(serainitialiséaveclesocket)
varin:Option[BufferedReader]=None//Fluxd'entrée(serainitialiséaveclesocket)
vallabel=newTextArea()
label.setEditable(false)
label.setLayoutX(40)//Positionhorizontale
label.setLayoutY(70)//Positionverticale
label.setPrefSize(370,120)
vallabel2=newLabel("Questions:")
label2.setLayoutX(30)//Positionhorizontale
label2.setLayoutY(50)
label2.setStyle("-fx-font-size:14px;-fx-font-weight:bold;")
vallabel3=newLabel("ClientQuiz")
label3.setLayoutX(130)//Positionhorizontale
label3.setLayoutY(0)
//Changerlatailleetlacouleurdutextedulabel
label3.setStyle("-fx-font-size:36px;-fx-font-family:'Algerian';-fx-text-fill:green;")//Tailleetcouleur
valtextField1=newTextField()
//Changerlatailledelapolicedutexte
textField1.setStyle("-fx-font-size:10px;")//Tailledepolicede18pixels
valtextField2=newTextField()
textField2.setStyle("-fx-font-size:10px;")
//RendreleTextField2nonmodifiable
textField2.setEditable(false)
textField2.setText(s"$s/10")//initialiselascoreazero

vallabelField1=newLabel("MaReponse")
labelField1.setStyle("-fx-font-size:14px;-fx-font-weight:bold;")

vallabelField2=newLabel("MonScore")

Code Complet(Java _ Python _ Scala) Page 19


vallabelField2=newLabel("MonScore")
labelField2.setStyle("-fx-font-size:14px;-fx-font-weight:bold;")

valaligne_field=newHBox(30)
aligne_field.getChildren.addAll(labelField1,textField1,labelField2,textField2)
aligne_field.setLayoutY(280)

valbutton1=newButton("Connecter")
button1.setStyle("-fx-background-color:green;-fx-text-fill:white;")
valbutton2=newButton("QuestionSuivante")
button2.setStyle("-fx-background-color:green;-fx-text-fill:white;")

valbutton3=newButton("Quitter")
button3.setStyle("-fx-background-color:green;-fx-text-fill:white;")

valaligne_button=newHBox(105)
aligne_button.getChildren.addAll(button1,button2,button3)
aligne_button.setLayoutY(360)

//PariteImplementationdelaLogique
button3.setOnAction(_=>Platform.exit())
button1.setOnAction(_=>{clientSocket=Some(newSocket("localhost",12345))//Connexionauserveur
out=clientSocket.map(socket=>newPrintWriter(socket.getOutputStream,true))
in=clientSocket.map(socket=>newBufferedReader(newInputStreamReader(socket.getInputStream)))
s=0
label.setText(Q1)
})

valQuestions=ArrayBuffer(Q1,Q2,Q3,Q4,Q5,Q6,Q7,Q8,Q9,Q10)
vari=0
button2.setOnAction(_=>{
if(!(textField1.getText().equals("A"))&!(textField1.getText().equals("B"))){
label.setText(Questions(i)+"\nEntrezsoitAouB")
}else{
i+=1
if(i>9){
label.setText("FINDUQUIZ")
}else{
if(clientSocket==None){
label.setText("Veuillezvousconnecterauserveur")
}else{
label.setText(Questions(i))//Afficherlaprochainequestion
}
}

try{
out.foreach(_.println(textField1.getText()))//Envoyerlaréponseauserveur
in.foreach{reader=>
valresponse=reader.readLine()//Lirelaréponseenvoyéeparleserveur
if(response==null){
//Silaconnexionestperdue,afficherunmessage
thrownewException("Connexionperdueavecleserveur.")
s=0
}
elseif(response=="true"){
s+=1

Code Complet(Java _ Python _ Scala) Page 20


}
}catch{
casee:Exception=>
//Afficherunmessagedansl'interfaceutilisateur
Platform.runLater(()=>{
label.setText(s"Erreur:${e.getMessage}")
})
in.foreach(_.close())
out.foreach(_.close())
clientSocket.foreach(_.close())
in=None
out=None
clientSocket=None
i=1
s=0

textField2.setText(s"$s/10")//Mettreàjourlescore
}
textField1.setText("")
})

valroot=newPane()//Conteneurvertical
root.getChildren.addAll(label,aligne_button,label2,label3,aligne_field)

valscene=newScene(root,450,400)
primaryStage.setTitle("ApplicationScalaavecJavaFX")
primaryStage.setScene(scene)
primaryStage.setResizable(false)//Empêcheleredimensionnementdelafenêtre
primaryStage.show()

}
}

Code Complet(Java _ Python _ Scala) Page 21

You might also like