Incohérence _numClients - Développement d'un serveur multithread simple
Bonjour minosis,
J'ai lu un article de Developpez.net sur la création d'un serveur multithread simple et j'ai décidé de m'inspirer de leur code pour créer mon propre serveur multithread. J'y ai ajouté un système de LogIn via un fichier qui contient tous les utilisateurs enregistrés, j'ai ajouté en plus du du Vector _tabclients deux autres vecteurs enregistrant le username du client et son adresse IP.
Cependant j'ai un problème par rapport au nombre retourné par la fonction addClient(). En effet il me retourne 49 au lieu de 0 lorsqu'un utilisateur est connecté. J'ai regardé plusieurs heures mon code sans savoir d'où provient l'erreur. Ce serait un grand plaisir si vous pouviez m'aider à trouver d'où vient cette incohérence qui fausse mon programme.
Avec ceci je vous joins le code mon programme serveur:
Code:
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| package com.stol3nd_hack_.server;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
public class Server {
private static int _nbClients = 0;
private static Vector _tabClients = new Vector();
private static Vector ip_clientArray = new Vector();
private static Vector usernameArray = new Vector();
public static void main(String[] args) {
// TODO Auto-generated method stub
Server server = new Server();
try{
Integer port;
if(args.length<=0) port = new Integer("25565");
else port = new Integer(args[0]);
ServerSocket ss = new ServerSocket(port.intValue());
printWelcome(port);
while(true){
Socket s_client = ss.accept();
new AuthenticateThread(s_client, server);
}
}catch(Exception e){}
}
synchronized public void sendAll(String message)
{
PrintWriter out; // declaration d'une variable permettant l'envoi de texte vers le client
for (int i = 0; i < _tabClients.size(); i++) // parcours de la table des connectés
{
out = (PrintWriter) _tabClients.elementAt(i); // extraction de l'élément courant (type PrintWriter)
if (out != null) // sécurité, l'élément ne doit pas être vide
{
// ecriture du texte passé en paramètre (et concaténation d'une string de fin de chaine si besoin)
out.println(message);
out.flush(); // envoi dans le flux de sortie
}
}
}
static private void printWelcome(Integer port){
System.out.println("------------------------------------");
System.out.println("STOL3ND Hacking Server : By STO Regin - Chatting Server");
System.out.println("------------------------------------");
System.out.println("Last Version : v0.01");
System.out.println("------------------------------------");
System.out.println("Beginning port : "+ port.toString());
System.out.println("------------------------------------");
}
synchronized public static int addClient(PrintWriter out, String username, String ipadress)
{
_nbClients++;
_tabClients.addElement(out);
usernameArray.addElement(username);
ip_clientArray.addElement(ipadress);
return _tabClients.size()-1;
}
synchronized public int getNbClients(){
return _nbClients; // retourne le nombre de clients connectés
}
synchronized public void delClient(int i) {
_nbClients--; // un client en moins ! snif
if (_tabClients.elementAt(i) != null) // l'élément existe ...
{
_tabClients.removeElementAt(i); // ... on le supprime
}
if (ip_clientArray.elementAt(i) != null) // l'élément existe ...
{
ip_clientArray.removeElementAt(i); // ... on le supprime
}
if (usernameArray.elementAt(i) != null) // l'élément existe ...
{
usernameArray.removeElementAt(i); // ... on le supprime
}
}
synchronized public boolean already_connected(String username){
if(usernameArray.contains(username)){
return true;
}else{
return false;
}
}
} |
AuthenticateThread.java :
Code:
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 80 81 82 83 84 85 86 87 88
| package com.stol3nd_hack_.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class AuthenticateThread implements Runnable{
private Thread _t;
private Socket s;
private Server server;
private PrintWriter out;
private BufferedReader in;
private boolean authenticate = false;
private String username;
private int num_client;
private String ip_client;
AuthenticateThread(Socket s_client, Server server) {
s = s_client;
this.server = server;
try
{
out = new PrintWriter(s.getOutputStream());
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
catch (IOException e){ }
_t = new Thread(this); // instanciation du thread
_t.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(!authenticate){
out.println("Enter your username : ");
out.flush();
username = in.readLine();
out.println("Enter your password : ");
out.flush();
String password = in.readLine();
String login = new String(username+"@"+password);
File ad_login = new File("ad_stol3nd.dat");
BufferedReader br = new BufferedReader(new FileReader(ad_login));
String line;
while ((line = br.readLine()) != null) {
if(line.equals(login)){
if(!server.already_connected(username)){
authenticate = true;
}
}
}
br.close();
if(!authenticate){
out.println("Identifiants incorrects! Réessayez! (Si vous êtes sûr de vos identifiants, vous êtes peut-être déjà connecté sur un autre appareil");
out.flush();
}
}
out.println("Connexion réussi!");
out.flush();
new ServerThread(s,server,username,s.getInetAddress().getHostAddress(),out,in);
} catch (IOException e) {try {s.close();} catch (IOException e1) {} e.printStackTrace();}
}
} |
ServerThread.java :
Code:
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 80
| package com.stol3nd_hack_.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ServerThread implements Runnable{
private Thread _t;
private Server server;
private Socket s;
private PrintWriter out;
private BufferedReader in;
private int num_client;
private String username;
private Scanner sc = new Scanner(System.in);
private String ipaddress;
ServerThread(Socket s, Server server, String username, String ipaddress, PrintWriter out, BufferedReader in){
this.server = server;
this.s = s;
this.username = username;
this.ipaddress = ipaddress;
this.out = out;
this.in = in;
try {
num_client = server.addClient(out, username, ipaddress);
out.println(num_client);
out.flush();
String new_client =in.readLine();
String msg = new_client.replace("sendall", "");
server.sendAll(msg);
_t = new Thread(this);
_t.start();
} catch (Exception e) {}
}
@Override
public void run() {
// TODO Auto-generated method stub
String msg_recu ="";
while(!msg_recu.equals("stop")){
try {
msg_recu = in.readLine();
System.out.println(msg_recu);
} catch (Exception e) {
server.delClient(num_client);
System.out.println(server.getNbClients());
System.exit(0);
try {
in.close();
out.close();
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
} |
Si vous avez besoin du code client, n'hésite pas à me le demander. Merci d'avance.