Ajouter un commentaire

Niroken

Hello,

Voici le petit Tchat client/serveur bien avancé avec la gestion des envois/réception de messages.

Il y a évidemment moyen d'optimiser ca : la je n'ai mis qu'une gestion très légère des exceptions et le code est un peu mélangé, on aurait pu factoriser ca un peu mieux, ceci dit, ca marche...je te tansmets donc le code complet :

Code client :

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.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

////////

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 mClientSocket = null;
	private String mClientNom;
	private List<ClientMessage> mClientsMessages;
	
/////////	

	
	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) {
					ClientMessage vClientMessage = new ClientMessage();
					vClientMessage.setClientNom(mClientNom);
					vClientMessage.setMessage(tenvoi.getText());
					
					trecuArea.append(vClientMessage.getClientNom() + " : ");
					trecuArea.append(vClientMessage.getMessage());
					trecuArea.append(System.getProperty("line.separator"));
					trecuArea.append(System.getProperty("line.separator"));
					
					mClientsMessages.add(vClientMessage);
				}
			}); 
		}
		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) {
					if (mClientSocket == null || mClientSocket.isClosed()) {
						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.mClientsMessages = new ArrayList<ClientMessage>();
		this.addWindowListener(new java.awt.event.WindowAdapter() { 
			
			public void windowClosing(java.awt.event.WindowEvent e) {      
				try {
						mClientSocket.close(); 
					} catch (Exception ex) {
						System.out.println(ex.getMessage());
					}
			}                                                                    
			                                        
			public void windowOpened(java.awt.event.WindowEvent e) {
				if (mClientSocket == null || mClientSocket.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 {
                	int vPortServeur = Integer.parseInt(ConfigReader.getInstance("client.properties").getProperty("serveur.port"));
                	String vIpServeur = ConfigReader.getInstance("client.properties").getProperty("serveur.ip");
                	mClientSocket = new Socket(vIpServeur, vPortServeur);
                    
                	if (authentificateWithServer(mClientSocket)) {
                		while (true) {
                			displayClientsConnected(mClientSocket);
                			sendMessagesToServer(mClientSocket);
                			receiveMessagesFromServer(mClientSocket);
                			
                			Thread.sleep(1000);
                		}
                	}
                	
                	mClientSocket.close();
    			} catch (Exception e) {
                    e.printStackTrace(); 
                }               
            }
      
        };
        
        vThread.start();
	}
	
	private boolean authentificateWithServer(Socket pSocket) throws Exception {
		mClientNom = JOptionPane.showInputDialog(this , "Veuillez enter un nom pour tchatter :");
		
		if (mClientNom != null) {
			PrintWriter out= new PrintWriter(pSocket.getOutputStream(), true);
	        out.write(mClientNom + "\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;
	}
	
	private 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")) {
        	dlm.addElement(req);
        }
        
        lpseudo.setModel(dlm);
	}
	
	private void sendMessagesToServer(Socket pSocket) throws Exception {
		ObjectOutputStream vObjectOutputStream = new ObjectOutputStream(pSocket.getOutputStream());
		vObjectOutputStream.writeObject(mClientsMessages);
		vObjectOutputStream.flush();
		
		mClientsMessages.clear();
	}
	
	private void receiveMessagesFromServer(Socket pSocket) throws Exception {
		ObjectInputStream vObjectInputStream = new ObjectInputStream(pSocket.getInputStream());
		List<ClientMessage> vClientsReceivedMessages = (List<ClientMessage>) vObjectInputStream.readObject();
		
		for (ClientMessage vClientMessageReceivedTmp : vClientsReceivedMessages) {
			trecuArea.append(vClientMessageReceivedTmp.getClientNom() + " : ");
			trecuArea.append(vClientMessageReceivedTmp.getMessage());
			trecuArea.append(System.getProperty("line.separator"));
			trecuArea.append(System.getProperty("line.separator"));
		}
	}

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

Code serveur :

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

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

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

	public void launchServer() {
		mClientsMessages = new HashMap<String, List<ClientMessage>>();
		
		try {
			int vPortServeur = Integer.parseInt(ConfigReader.getInstance("serveur.properties").getProperty("serveur.port"));
			ServerSocket vServerSocket = new ServerSocket(vPortServeur);
		    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);
		        			   receiveMessagesFromClient(vSocket, mCurrentThreadNomClient);
		        			   sendMessagesToClient(vSocket, mCurrentThreadNomClient);
		        		   }
		        		   
		        		   vSocket.close();
		        	   } catch (Exception e) {
		        		   mClientsMessages.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 (mClientsMessages.containsKey(vNomClient)) {
        	out.write("KO\r\n");
            out.flush();
            pSocket.close();
            return null;
        } else {
        	mClientsMessages.put(vNomClient, new ArrayList<ClientMessage>());
        	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 : mClientsMessages.keySet()) {
				out.write(vClientNomTmp + "\r\n");
			}
			
			out.write(sEndCommand);
			out.flush();
		}
	}
	
	private void sendMessagesToClient(Socket pSocket, String pCurrentClient) throws Exception {
		ObjectOutputStream vObjectOutputStream = new ObjectOutputStream(pSocket.getOutputStream());
		vObjectOutputStream.writeObject(mClientsMessages.get(pCurrentClient));
		vObjectOutputStream.flush();
		
		mClientsMessages.get(pCurrentClient).clear();
	}
	
	private void receiveMessagesFromClient(Socket pSocket, String pCurrentClient) throws Exception {
		ObjectInputStream vObjectInputStream = new ObjectInputStream(pSocket.getInputStream());
		List<ClientMessage> vClientsReceivedMessages = (List<ClientMessage>) vObjectInputStream.readObject();
		
		for (String vClientNom : mClientsMessages.keySet()) {
			if (!vClientNom.equals(pCurrentClient)) {
				mClientsMessages.get(vClientNom).addAll(vClientsReceivedMessages);
			}
		}
	}
	
}  //  @jve:decl-index=0:visual-constraint="10,10"

ConfigReader :



import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class ConfigReader {
    
    private Properties mProperties;
    private static ConfigReader sInstance;
        
    private ConfigReader(String pFilePropertiesName) throws IOException {
        readConfig(pFilePropertiesName);
    }
    
    public static ConfigReader getInstance(String pFilePropertiesName) {
        if (sInstance == null) {
            try {
                sInstance = new  ConfigReader(pFilePropertiesName);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Impossible de lire le fichier " + pFilePropertiesName);
            }
        }
        
        return sInstance;
    }
        
    private void readConfig(String pFilePropertiesName) throws IOException {
        mProperties = new Properties();
        FileInputStream vFileInputStream = new FileInputStream(pFilePropertiesName);
        mProperties.load(vFileInputStream);
        vFileInputStream.close();
    }

    public String getProperty(String pKey) {
        return mProperties.getProperty(pKey);
    }
    
    public Properties getProperties() {
        return mProperties;
    }
    
    public static String getClasspathResource(String pResourcePath) {
        String vPath = pResourcePath;
        
        if (vPath.startsWith("/")) {
            vPath = vPath.substring(1);
        }
        
        try {
            return Thread.currentThread().getContextClassLoader().getResource(vPath).getPath().replaceAll("%20", " ");
        } catch (Exception pException) {
            throw new RuntimeException("La ressource " + pResourcePath + " n est pas dans le classpath !");
        }
    }
    
}

ClientMessage :



import java.io.Serializable;

public class ClientMessage implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private String mMessage;
	private String mClientNom;
	
	public String getMessage() {
		return mMessage;
	}
	
	public void setMessage(String pMessage) {
		mMessage = pMessage;
	}
	
	public String getClientNom() {
		return mClientNom;
	}
	
	public void setClientNom(String pClientNom) {
		mClientNom = pClientNom;
	}	
	
}

Ce tchatter est fonctionnel, ceci dit, je n'ai pas géré l'envoi de messages privés :) , ca fera un bon exercice pour toi :)

Bonne chance,
Niroken

Filtered HTML

Plain text

CAPTCHA
Cette question permet de vérifier que vous n'êtes pas un robot spammeur :-)
 Y   Y  L     W     W  PPPP   TTTTTT 
Y Y L W W P P TT
Y L W W W PPPP TT
Y L W W W P TT
Y LLLL W W P TT