Ajouter un commentaire

Niroken

Hello,

Non rassures toi, j'ai réussit a me débrouiller, sauf que comme cela est un peu complexe.. je pense qu'on va procéder par étape.

D'une part, la base de données pour l'instant ce n'est pas une bonne idée..puisqu'elle ne fait que contenir des infos style "login" "password".
Mais créer un compte ne nous apporte rien puisqu on peut en créer un à chaque fois et comme aucune autre info n'est persistée du genre "amis ou contacts" favoris... c'est inutile.

Le serveur seul va gérer les connexions et savoir qui est connecté ou pas.

Donc la première étape, c'est justement la facon dont le serveur gère les connexions :
1) On allume le serveur en attente de connexions et garde en mémoire une liste de noms qui correspond au nom de chaque client.
2) Un client se connecte : L'utilisateur saisit un nom pour la durée de son tchat et l'envoit au serveur.
3)Le serveur recoit le nom, si le nom est deja présent dans la liste, alors le serveur dit que c'est pas bon au client et le socket se ferme. Si c est bon le serveur rajoute son nom a cette liste
4)Le client connecté envoit périodiquement une requete au serveur pour lui demander de reactualiser sa liste de connectés.
5)Le serveur renvoit au client cette liste.

Pour l'instant aucune partie envoie reception de message de tchat n'est gérée, mais tu verras bien que la liste d'affichage des clients est bien reactualisée a chaque fois qu 'un client se connecte/déconecte.

Code client (a partir du tien) :

import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;

import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JList;
import java.awt.Insets;
//////////
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;

////////

public class client extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JPanel jPanel = null;
	private JTextArea tenvoi = null;
	private JTextArea trecuArea = null;
	private JButton vButton = null;
	private JLabel jLabel1 = null;
	private JButton benvoyer = null;
	private JList lpseudo = null;    
////////Socket.......
	private Socket mClient = null;
	private String mNomClient;
	
/////////	

	
	private JPanel getJPanel() {
		if (jPanel == null) {
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 2;
			gridBagConstraints.gridy = 2;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.fill = GridBagConstraints.BOTH;
			gridBagConstraints1.gridy = 0;
			gridBagConstraints1.weightx = 9.0;
			gridBagConstraints1.weighty = 1.0;
			gridBagConstraints1.gridwidth = 1;
			gridBagConstraints1.insets = new Insets(0, 0, 0, 0);
			gridBagConstraints1.ipadx = 0;
			gridBagConstraints1.gridx = 0;
			GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.fill = GridBagConstraints.BOTH;
			gridBagConstraints11.gridy = 0;
			gridBagConstraints11.weightx = 1.0;
			gridBagConstraints11.weighty = 1.0;
			gridBagConstraints11.ipadx = 0;
			gridBagConstraints11.ipady = 0;
			gridBagConstraints11.anchor = GridBagConstraints.WEST;
			gridBagConstraints11.gridwidth = 1;
			gridBagConstraints11.insets = new Insets(0, 1, 0, 0);
			gridBagConstraints11.gridx = 2;
			GridBagConstraints gridBagConstraints10 = new GridBagConstraints();
			gridBagConstraints10.gridx = 1;
			gridBagConstraints10.anchor = GridBagConstraints.NORTH;
			gridBagConstraints10.gridy = 2;
			GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
			gridBagConstraints9.gridx = 1;
			gridBagConstraints9.gridy = 0;
			jLabel1 = new JLabel();
			jLabel1.setText("            ");
			GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
			gridBagConstraints8.fill = GridBagConstraints.HORIZONTAL;
			gridBagConstraints8.gridy = 2;
			gridBagConstraints8.weightx = 1.0;
			gridBagConstraints8.weighty = 0.0;
			gridBagConstraints8.gridwidth = 1;
			gridBagConstraints8.anchor = GridBagConstraints.NORTH;
			gridBagConstraints8.gridheight = 1;
			gridBagConstraints8.insets = new Insets(6, 4, 5, 0);
			gridBagConstraints8.gridx = 0;
			GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
			gridBagConstraints6.gridx = 0;
			gridBagConstraints6.gridy = 1;
			//jLabel = new JLabel();
			//jLabel.setText("            ");
			jPanel = new JPanel();
			jPanel.setLayout(new GridBagLayout());
			//jPanel.add(jLabel, gridBagConstraints6);
			jPanel.add(getTenvoi(), gridBagConstraints8);
			jPanel.add(jLabel1, gridBagConstraints9);
			jPanel.add(getBenvoyer(), gridBagConstraints10);
			jPanel.add(getLpseudo(), gridBagConstraints11);
			jPanel.add(getTrecuArea(), gridBagConstraints1);
			jPanel.add(getVButton(), gridBagConstraints);
			
			

		}
			return jPanel;
	}
	
	private JTextArea getTenvoi() {
		if (tenvoi == null) {
			tenvoi = new JTextArea();
			//tenvoi.WIDTH=5.0;
		}
		return tenvoi;
	}

	private JButton getBenvoyer() {
		if (benvoyer == null) {
			benvoyer = new JButton();
			benvoyer.setText("Envoyer");
			benvoyer.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					
				}
			}); 
		}
		return benvoyer;
	}

	
	private JList getLpseudo() {
		if (lpseudo == null) {
			lpseudo = new JList();
		}
		return lpseudo;
	}

	
	
	private JTextArea getTrecuArea() {
		if (trecuArea == null) {
			trecuArea = new JTextArea();
			trecuArea.setEnabled(false);
		}  
		return trecuArea;
	}

	 
	private JButton getVButton() {
		if (vButton == null) {
			vButton = new JButton();
			vButton.setText("Tchatter");
			vButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					communicateWithServer();
				}
			});
		} 
		return vButton;    
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);  
		/////////////////////////////////////
		
		////////////////////////////////////////////:
		
		SwingUtilities.invokeLater(new Runnable() { 
			public void run() {
				client thisClass = new client(); 
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}

	public client (){
		super();
		initialize();
		this.setBackground(Color.GREEN);
	}

	private void initialize() {
		this.setSize(648, 441);
		this.setContentPane(getJContentPane());
		this.setTitle("CLIENT");
		this.addWindowListener(new java.awt.event.WindowAdapter() { 
			
			public void windowClosing(java.awt.event.WindowEvent e) {      
				try {
						mClient.close(); 
					} catch (Exception ex) {
						System.out.println(ex.getMessage());
					}
			}                                                                    
			                                        
			public void windowOpened(java.awt.event.WindowEvent e) {
				if (mClient == null || mClient.isClosed()) {
					communicateWithServer();
				}
			}   
		});    
	}

	private JPanel getJContentPane() {         
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getJPanel(), BorderLayout.CENTER);
		}
		return jContentPane;
	}
	
	private void communicateWithServer() {
		Thread vThread = new Thread() {
	           
            public void run () {
                try {
                	mClient = new Socket("localhost", 3500);
                    
                	if (authentificateWithServer(mClient)) {
                		while (true) {
                			displayClientsConnected(mClient);
                			
                			Thread.sleep(1000);
                		}
                	}
                	
                	mClient.close();
    			} catch (Exception e) {
                    e.printStackTrace(); 
                }               
            }
      
        };
        
        vThread.start();
	}
	
	public boolean authentificateWithServer(Socket pSocket) throws Exception {
		mNomClient = JOptionPane.showInputDialog(this , "Veuillez enter un nom pour tchatter :");
		
		if (mNomClient != null) {
			PrintWriter out= new PrintWriter(pSocket.getOutputStream(), true);
	        out.write(mNomClient + "\r\n");
	        out.flush();
	        
	        BufferedReader in=new BufferedReader(new InputStreamReader(pSocket.getInputStream()));
	        String vReponse = in.readLine();
	        
	        if (vReponse.startsWith("OK")) {
	        	return true;
	        } else {
	        	JOptionPane.showMessageDialog(this, "Ce nom existe deja !", "Warning", JOptionPane.WARNING_MESSAGE);
			}
		}
		
		return false;
	}
	
	public void displayClientsConnected(Socket pSocket) throws Exception {
		PrintWriter out= new PrintWriter(pSocket.getOutputStream(), true);
        out.write("DISPLAYCLIENTS\r\n");
        out.flush();
        
        BufferedReader in=new BufferedReader(new InputStreamReader(pSocket.getInputStream()));
        String req=new String();
        
        DefaultListModel dlm=new DefaultListModel();
        while(!(req=in.readLine()).startsWith("ENDCOMMAND")) {
        	System.out.println(req);
        	dlm.addElement(req);
        }
        
        lpseudo.setModel(dlm);
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"

Code serveur (Refondu complètement) :

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import java.util.HashMap;
//////////////////
public class serveur {
	
	private static String sEndCommand = "ENDCOMMAND\r\n";
	
	private HashMap<String, Object> mClients;

	public static void main(String[] args) {
		new serveur().launchServer();
	} 

	public void launchServer() {
		mClients = new HashMap<String, Object>();
		
		try {
			ServerSocket vServerSocket = new ServerSocket(3500);
		    while(true) {
		        final Socket vSocket = vServerSocket.accept();
		        
		        Thread vThread = new Thread() {
		           private String mCurrentThreadNomClient;
		        	
		           public void run() {
		        	   try {
		        		   mCurrentThreadNomClient = receiveAuthentificationFromClient(vSocket);
		        		   
		        		   while (!vSocket.isClosed()) {
		        			   sendListClientsConnectedToClient(vSocket);
		        		   }
		        		   
		        		   vSocket.close();
		        	   } catch (Exception e) {
		        		   mClients.remove(mCurrentThreadNomClient);
		        		   e.printStackTrace();
		        	   }
		           }
		           
		       };
		        
		       vThread.start();
		    }
		} catch (Exception e) { 
			e.printStackTrace();
		}
	}	
	
	private String receiveAuthentificationFromClient(Socket pSocket) throws Exception {
		BufferedReader vInputBufferedReader = new BufferedReader(new InputStreamReader(pSocket.getInputStream()));
        String vNomClient = vInputBufferedReader.readLine();
        
        PrintWriter out= new PrintWriter(pSocket.getOutputStream(), true);
                
        if (mClients.containsKey(vNomClient)) {
        	out.write("KO\r\n");
            out.flush();
            pSocket.close();
            return null;
        } else {
        	mClients.put(vNomClient, null);
        	out.write("OK\r\n");
            out.flush();
        }
        
        return vNomClient;
	}
	
	private void sendListClientsConnectedToClient(Socket pSocket) throws Exception {
		BufferedReader vInputBufferedReader = new BufferedReader(new InputStreamReader(pSocket.getInputStream()));
		String vRequest = vInputBufferedReader.readLine();
				
		if (vRequest.startsWith("DISPLAYCLIENTS")) {
			PrintWriter out= new PrintWriter(pSocket.getOutputStream(), true);
	        
			for (String vClientNomTmp : mClients.keySet()) {
				out.write(vClientNomTmp + "\r\n");
			}
			
			out.write(sEndCommand);
			out.flush();
		}		
	}
	
}  //  @jve:decl-index=0:visual-constraint="10,10"

Je te laisse regarder ce code, si tu as tt compris tu me dis et on passera à l étape deux : l'envoi reception de données de tchat.

Bonne chance,
Niroken

Filtered HTML

Plain text

CAPTCHA
Cette question permet de vérifier que vous n'êtes pas un robot spammeur :-)
 BBBB   DDD   Y   Y  L     V     V 
B B D D Y Y L V V
BBBB D D Y L V V
B B D D Y L V V
BBBB DDD Y LLLL V