PROGRAMMATION
RÉSEAU: CODE SOURCE
Joseph NDONG
Faculté des Sciences et Techniques
Département de Mathématiques et Informatique
Joseph NDONG UCAD DAKAR
SENEGAL 1
PLAN DU COURS
Je donne ici des exemples de code pour l’utilisation des
Sockets en version multithréadé et RMI.
Joseph NDONG UCAD DAKAR
SENEGAL 2
Exemple multiutilisateurs de Socket Serveur TCP
package [Link];
import [Link].*;
import [Link].*;
//Cette classe multithreadré sert a traiter plusieur requetes clients a la fois
public class TCPserver extends Thread{
protected BufferedReader in;
protected PrintWriter pw;
private Socket soc;
String s;
/**cree un socket d’ecoute pour chaque client qui se connecte et on
initialise les deux fux d'I/O*/
public TCPserver (Socket soc) {
3
try {
[Link] = soc;
[Link] = new BufferedReader
(new InputStreamReader([Link]()));
[Link]= new PrintWriter ([Link](), true);
}
catch (Exception e) {[Link] ( "Pb lors de l'ecoute"); }
}
/*lance le traitement de la requete pour le client qui se connecte*/
public void run (){
try {
// tant que le client n'a pa envoye une chaine le traitement ne demarre pas
try {
traitement ();
[Link](1000);
}
catch (InterruptedException e){
[Link]("Interruption grave du processus");
} Joseph NDONG UCAD DAKAR
SENEGAL 4
}
catch (Exception er){}
}
/*pour recuperer la requete du client c a d la chaine envoyee*/
public String reception(){
String d=null;
try {
d=[Link]();
return d;
}
catch (Exception e){
err .println("Erreur reading ...") ;[Link]();
return null;
}
}
Joseph NDONG UCAD DAKAR
SENEGAL 5
/*pour le traitement proprement dit de la requete*/
public void traitement() {
try{
s = [Link]();
if (s==null) {out .println("Fin du service
avec"+[Link]()+ " Merci") ;[Link]() ;
}
else { [Link](s);
String revline=new StringBuffer(s).reverse().toString();
if (out != null)
[Link]("[Server Answer]>>> " + revline);
[Link]() ;//fermer a la fin du traitement
}
Joseph NDONG UCAD DAKAR
SENEGAL 6
catch (Exception e) { err .println ("Erreur traitement ...") ;
[Link]() ;}
}
/*Méthode principale*/
public static void main (String args [ ]) throws Exception{
[Link] ss=new [Link] (2000);
[Link]("Demarrage serveur sur le port
"+[Link]() + "....");
while (true) {
Socket s=[Link]();
[Link]("Traitement serveur...avec le
client"+[Link]());
/*Lancement du programme serveur*/
new TCPserver(s).start();
}
}
} Joseph NDONG UCAD DAKAR
SENEGAL 7
Exemple multiutilisateurs de Client TCP
package [Link];
import [Link].*;
import [Link].*;
import [Link];
public class TCPClienThread extends Thread {
Socket s;
Scanner entree=null;
BufferedReader sin =null;
PrintWriter sout =null;
public TCPClienThread (){}
public void run(){
try {
String line;
while (true) {
s = new Socket("localhost",2000);
[Link](1000);
Joseph NDONG UCAD DAKAR
SENEGAL 8
[Link]("Connected to " + [Link]() + " on port "
+ [Link]());
sin = new BufferedReader
(new InputStreamReader([Link]()));
sout = new PrintWriter([Link](), true);
[Link]("[Client Ask] > > >");
entree = new Scanner([Link]);
line = [Link]();
if ([Link](""))
{
[Link]() ;
[Link]("Client: je m arrete");
break;
}
else { [Link](line);
[Link]() ;
Joseph NDONG UCAD DAKAR
SENEGAL 9
line = [Link]();
[Link]("recu du serveur: " + line);
}
}
}
catch (Exception dd){
[Link]("probleme d'enfrmissement du Thread...");
}
finally{
try { // dans tous les cas on ecrase le socket, security impose
[Link]();
}
catch (Exception er){}
}
}
public static void main (String[] args) {
// demarrage d’un client
new TCPClienThread ().start();
}
} 10
Exemple de mini serveur banquaire RMI
package rmibanque;
import [Link];
//interface distante
public interface Banque extends [Link] {
public void creerCompte(String prenom, String nom, long numero, double solde,
double decouvert) throws RemoteException ;
public void retirer(long numero,double montant) throws RemoteException ;
public void deposer(long numero,double montant) throws RemoteException ;
public void imprimeHistorique(long numero) throws RemoteException ;
public double getDecouvert(long numero) throws RemoteException ;
public double getSolde(long numero) throws RemoteException ;
public long getNumero(long numero) throws RemoteException ;
// public Compte getCompteFromNumero(long numero) throws RemoteException ;
public boolean controlNumeroCompte(long numero) throws RemoteException ;
}
Joseph NDONG UCAD DAKAR
SENEGAL 11
La classe Compte est locale au serveur, les clients distants n’y ont pas accès,
package rmibanque;
public class Compte{
private String prenom,nom;
private double solde;
private double solde ;
private lonh numero;
HashMap<String, Compte> clients=new HashMap<> ( );
public Compte (long numerp,String prenom, String nom,int age, double solde){
[Link]=numero;
[Link]=prenom;
[Link]=nom;
[Link]=age;
[Link]=solde;
clients,put(numero+" ",this);
}
public void retirer (double m) { [Link] -=m;}
public void deposer (double m) {[Link]+=m;}
public double getSolde ( ) { return [Link];}
Joseph NDONG UCAD DAKAR
} SENEGAL 12
Voici la classe de l’objet distant:
package rmibanque;
public class BanqueImpl extends [Link]
implements Banque,[Link] {
/*tous les clients seront en mémoire dans cette table*/
static [Link] clients = new [Link] ( );
public BanqueImpl ([Link] clients) throws [Link] {
super ( );
[Link] =clients;
}
Joseph NDONG UCAD DAKAR
SENEGAL 13
public Compte getCompteFromNumero(long numero){
Compte res = null;
[Link] enu=[Link] ( );
while ([Link]()){
Object cle = [Link]();
long clenum=[Link](cle+"") ;
if (clenum = = numero)
{ res=(Compte)[Link](cle);
break;
}
}
return res;
public static [Link] initCompteClients ( ){
return clients;
}
Joseph NDONG UCAD DAKAR
SENEGAL 14
/**
*
* @param numero long le nuemro du nouveau compte a cree
* @return boolean si le numero existe deja boollean=false sinon boolean =true
*/
public boolean controlNumeroCompte(long numero){
/*ATTENTION: il ne faut pas faire la verif a partir de BDD, cela bloquerait le server
il faut plutot examiner les comptes disponibles dans le Hashtable.
En effet les methodes declarees dans l'objet distant ne doivent pas manipuler
JDBC(non serializable)*/
Compte cc=getCompteFromNumero(numero) ;
boolean b= false;
if (cc==null) b= true;
return b;
}
Joseph NDONG UCAD DAKAR
SENEGAL 15
/**
* Pour ouvrir un nouveau compte client et l'enregistrer dans la base de donnees
* @param prenom String
* @param nom String
* @param numero long
* @param solde double
* @param decouvert double
* @throws RemoteException
*/
public void creerCompte (String prenom,String nom,long numero,double solde,
double decouvert)
throws [Link]
{
try{
new Compte(prenom, nom, numero, solde, decouvert);
}
catch (Exception e){}
}
Joseph NDONG UCAD DAKAR
SENEGAL 16
public void deposer (long numero,double montant)throws [Link] {
Object d=[Link](numero+"");
Compte c=(Compte)d;
try{
//au lieu de faire [Link](montant); il faut plutot lancer un thead synchonise
// avec l operation de retrait puis retrait et depot ne doivent en aucun
//cas se passer simultanement
ThreadCompteDepot td= new ThreadCompteDepot(c, numero, montant);
[Link]();
}
catch (Exception cd) {}
Joseph NDONG UCAD DAKAR
SENEGAL 17
public void retirer(long numero,double montant){
try { Object d=[Link](numero+"");
Compte c=(Compte)d;
try {
//au lieu de faire [Link](montant); il faut plutot lancer un thead synchonise
// avec l operation de depot puis retrait et depot ne doivent en aucun
//cas se passer simultanement
ThreadCompteRetrait tr= new ThreadCompteRetrait(c, numero, montant);
[Link]();
}
catch (Exception cd) {}
}
catch (Exception d){}
}
Joseph NDONG UCAD DAKAR
SENEGAL 18
public void imprimeHistorique(long numero) throws [Link] {
Object d=[Link](numero+"");
Compte c=(Compte)d;
[Link]();
}
public double getDecouvert(long numero) throws [Link] {
Object d=[Link](numero+"");
Compte c=(Compte)d;
double x= [Link]();
return x;
}
public double getSolde(long numero) throws [Link] {
Object d=[Link](numero+"");
Compte c=(Compte)d;
double k= [Link]();
return k;
}
Joseph NDONG UCAD DAKAR
SENEGAL 19
public long getNumero (long numero) throws [Link] {
Object d=[Link](numero+"");
Compte c=(Compte)d;
long k= [Link]() ;
return k;
}
Joseph NDONG UCAD DAKAR
SENEGAL 20
public static [Link] getClientsFromBD(){
[Link] con= null; [Link] st=null;
[Link] rs1= null;
try {
[Link]("[Link]");
}
catch (Exception f){[Link] ( "Driver non charge"); }
try{
con=[Link]("jdbc:mysql://localhost/employe","joseph","joe");
}
catch (Exception f){[Link]("Connection impossible"); }
try {
st= [Link](con);
rs1= [Link]("select * from client") ;
if(rs1!=null)
while([Link]() ){
String o1=(String)[Link]("prenom") ;
String o2=(String)[Link]("nom") ;
long o3=[Link]([Link]("numero")+"") ;
// double o4=[Link]([Link]("solde")+"") ;
// double o5=[Link]([Link]("decouvert")+"") ;
[Link](o3+"",new Compte
Joseph NDONG UCAD(o1,o2,o3,0,0))
DAKAR ;
SENEGAL 21
}
}
catch (Exception f){[Link](" Error extrait clients BD "+[Link]() );
[Link](); }
try{
[Link]();
// [Link]();
[Link]() ;
[Link]() ;
}
catch (Exception e){}
return [Link]();
}
Joseph NDONG UCAD DAKAR
SENEGAL 22
public static void enregClientBase(String prenom,String nom,long numero,
double solde, double decouvert) throws [Link] {
[Link] con=null;
[Link] st=null;
try {
[Link]("[Link]");
}
catch (Exception f){[Link]("Driver non charge"); }
try{ [Link] adr=[Link] .getByName("joesden");
String adresse=[Link]();
con=[Link]("jdbc:mysql://localhost/employe","root","");
}
catch (Exception f){[Link]("Connection impossible"); }
try{
st= [Link](con);
[Link]("Insert into client VALUES ('"+prenom+"','"+nom+"','"+numero+"')") ;
[Link]("Insert into compte VALUES ('"+numero+"','"+solde+"','"+decouvert+"')")
;
}
Joseph NDONG UCAD DAKAR
SENEGAL 23
catch (Exception f){[Link] (null,"Statement Error"); }
try{
[Link]() ;
[Link]() ;
}
catch (Exception e){}
}// fin de la methode enregClientBase
Joseph NDONG UCAD DAKAR
SENEGAL 24
public static void updateCompteClient(long numero,double solde)
throws [Link] {
[Link] con=null;
[Link] st=null;
try{
[Link]("[Link]");
}
catch(Exception f){[Link](null,"Driver non charge"); }
try{
con=[Link]("jdbc:mysql://localhost/employe","root","");
}
catch(Exception f){[Link](null,"Connection impossible"); }
try{
st= [Link](con);
[Link]("UPDATE compte SET solde='"+ solde+"'where numero='"+numero +"'");
}
catch(Exception f){[Link](null,"Statement Error"); }
Joseph NDONG UCAD DAKAR
SENEGAL 25
try{
[Link] ( ) ;
[Link] ( ) ;
}
catch(Exception e) { }
}// fin de la methode updateCompteClient
}// fin de la classe serveur
REMARQUE
Vous créerez la classe utilitaire ConnectBase qui gère l’accès à votre BD. Vous pouvez
aussi créer un exemple simple de client sous forme console ou sous forme GUI.
Joseph NDONG UCAD DAKAR
SENEGAL 26
Une classe principale pour démarrer le serveur bancaire:
package rmibanque;
public class ServerBank implements Runnable {
public void run ( ){
try{
[Link] ("demarrage serveur banque ....");
[Link] cl = [Link]();
BanqueImpl bi = new BanqueImpl (cl);
//[Link] ad=[Link] .getByName("joesden");
//String adhost=[Link]();
// [Link]("rmi://"+adhost+"/comptejoe", bi);
//[Link]("rmi://[Link]/comptejoe", bi);
[Link]("rmi://localhost/comptejoe", bi);
[Link](" serveur banque demarre !!!");
}
catch (Exception er){[Link]("Erreur serveur : "+[Link]() );
[Link]("Erreur serveur STACK TRACE: " );[Link]() ;
}
}
Joseph NDONG UCAD DAKAR
SENEGAL 27
public void start(){
Thread t= new Thread (this);
[Link] ( ) ;
}
public static void main(String[ ] args) throws [Link] {
[Link] (new RMISecurityManager ( )) ;
try{
ServerBank server = new ServerBank ( );
[Link] ( ) ;
}
catch (Exception e){[Link]("Erreur Thread : "+[Link] ( ) ); ;}
}
} // fin de la classe Main
Joseph NDONG UCAD DAKAR
SENEGAL 28