LMAGallois 3 years ago
parent
commit
9a77e9149b

+ 3
- 4
Application/Clavardage/bin/.gitignore View File

@@ -1,4 +1,3 @@
1
-/UserListeningThreadTCP.class
2
-/UserListeningThreadUDP.class
3
-/UserConnexionthreadTCP.class
4
-/Database.class
1
+/controller/
2
+/model/
3
+/view/

BIN
Application/Clavardage/bin/RemoteUser.class View File


BIN
Application/Clavardage/bin/User.class View File


+ 0
- 76
Application/Clavardage/src/Database.java View File

@@ -1,76 +0,0 @@
1
-import java.sql.Connection;
2
-import java.sql.DriverManager;
3
-import java.sql.ResultSet;
4
-import java.sql.SQLException;
5
-import java.sql.Statement;
6
-
7
-public class Database {
8
-	private Statement statement;
9
-	private Connection con;
10
-	
11
-	public Statement getStatement() {
12
-		return this.statement;
13
-	}
14
-	
15
-	public void close () throws SQLException {
16
-		this.statement.close();
17
-		this.con.close();
18
-		
19
-	}
20
-
21
-	
22
-	public void Database() {
23
-		try {
24
-			Class.forName("java.sql.Driver");
25
-			System.out.println("coucou");
26
-		} catch (ClassNotFoundException e) {
27
-			System.out.println("probleme avec le driver");
28
-			e.printStackTrace();
29
-		}
30
-		try {
31
-			this.con=DriverManager.getConnection("jdbc:mysql://srv-bdens.insa-toulouse.fr:3306","tp_servlet_003","povu3Ma2");
32
-			System.out.println("coucou");
33
-		} catch (SQLException e) {
34
-			System.out.println("co pas établit");
35
-			e.printStackTrace();
36
-		}
37
-
38
-		try {
39
-			this.statement=this.con.createStatement();
40
-			System.out.println("coucou");
41
-		} catch (SQLException e) {
42
-			System.out.println("statement pas établit");
43
-			e.printStackTrace();
44
-		}
45
-		
46
-		int nb_changed_rows=0;
47
-		try {
48
-			nb_changed_rows = statement.executeUpdate("CREATE DATABASE base");
49
-			System.out.println("coucou");
50
-		} catch (SQLException e) {
51
-			System.out.println("base de données pas établit");
52
-			e.printStackTrace();
53
-		}
54
-		try {
55
-			nb_changed_rows = statement.executeUpdate("USE base");
56
-			System.out.println("coucou");
57
-		} catch (SQLException e) {
58
-			System.out.println("use base  pas établit");
59
-			e.printStackTrace();
60
-		}
61
-		
62
-		try {
63
-			nb_changed_rows = statement.executeUpdate("CREATE TABLE chat (user_IPcode1 INTEGER, user_IPcode2 INTEGER, Message STRING, date STRING)");
64
-			System.out.println("coucou");
65
-		} catch (SQLException e) {
66
-			System.out.println("table non créée");
67
-			e.printStackTrace();
68
-		}
69
-
70
-		if (nb_changed_rows==0){
71
-			System.out.println("la modification n'a pas eu lieue");
72
-		};
73
-		
74
-	}
75
-
76
-}

+ 0
- 118
Application/Clavardage/src/Historique.java View File

@@ -1,118 +0,0 @@
1
-import java.sql.Connection;
2
-import java.sql.Date;
3
-import java.sql.DriverManager;
4
-import java.sql.ResultSet;
5
-import java.sql.ResultSetMetaData;
6
-import java.sql.SQLException;
7
-import java.sql.Statement;
8
-import java.util.Calendar;
9
-
10
-public class Historique {
11
-	private Database bdd;
12
-	private ResultSet rs_received;
13
-	private ResultSet rs_sent;	
14
-	private ResultSetMetaData rsmd_received;
15
-	private ResultSetMetaData rsmd_sent;
16
-	
17
-	public void setRSReceived(ResultSet rs) {
18
-		this.rs_received=rs;
19
-	}
20
-	
21
-	public void setRSSent(ResultSet rs) {
22
-		this.rs_sent=rs;
23
-	}
24
-	
25
-	public ResultSet getRSSent() {
26
-		return this.rs_sent;
27
-	}
28
-	
29
-	public ResultSet getRSReceived() {
30
-		return this.rs_received;
31
-	}
32
-	
33
-	public void setRSMDReceived(ResultSetMetaData rsmd) {
34
-		this.rsmd_received=rsmd;
35
-	}
36
-	public void setRSMDSent(ResultSetMetaData rsmd) {
37
-		this.rsmd_sent=rsmd;
38
-	}
39
-	public ResultSetMetaData getRSMDReceived() {
40
-		return this.rsmd_received;
41
-	}
42
-	public ResultSetMetaData getRSMDSent() {
43
-		return this.rsmd_sent;
44
-	}
45
-	
46
-	public void saveMessage(User user1, RemoteUser user2, String input, String date) {
47
-		System.out.println("coucou");
48
-
49
-		int nb_changed_rows=0;
50
-		try {
51
-			nb_changed_rows = this.bdd.getStatement().executeUpdate("INSERT INTO chat values ("+user1.getIPcode()+","+user2.addIP+","+input+","+date+")");
52
-		} catch (SQLException e) {
53
-			System.out.println("insertion pas établit");
54
-			e.printStackTrace();
55
-		}
56
-		//nb_changed_rows = this.bdd.getStatement().executeUpdate("DELETE FROM table where name=‘noname’");
57
-		if (nb_changed_rows==0){
58
-			System.out.println("la modification n'a pas eu lieue");
59
-		}
60
-	}
61
-	
62
-	public String retrieveMessage(User user1, RemoteUser user2) throws SQLException {
63
-		this.setRSSent(this.bdd.getStatement().executeQuery("SELECT"+user1.getIPcode()+","+user2.getIPcode()+",? ,? FROM table"));
64
-		this.setRSReceived(this.bdd.getStatement().executeQuery("SELECT"+user2.getIPcode()+","+user1.getIPcode()+",?, ? FROM table"));
65
-		//this.setRSMDSent(this.getRSSent().getMetaData());
66
-		//this.setRSMDReceived(this.getRSReceived().getMetaData());
67
-	    boolean encore1 = this.getRSSent().next();
68
-	    boolean encore2 = this.getRSReceived().next();
69
-	    String message=null;
70
-	    String[] string1=null;
71
-	    String[] string2=null;
72
-	    Calendar date1=Calendar.getInstance();
73
-	    Calendar date2=Calendar.getInstance();
74
-	    while(encore1 || encore2) {
75
-	    	while (this.getRSSent().getInt(1)!=user2.getIPcode()) {
76
-	    		encore1=this.getRSSent().next();
77
-	    	}
78
-    		string1=this.getRSSent().getString(3).split(" ");
79
-    		date1.set(Integer.valueOf(string1[0]), Integer.valueOf(string1[1]), Integer.valueOf(string1[2]),Integer.valueOf(string1[3]), Integer.valueOf(string1[4]), Integer.valueOf(string1[5]));
80
-
81
-
82
-	    	while (this.getRSReceived().getInt(0)!=user1.getIPcode()) {
83
-		    	encore2=this.getRSReceived().next();
84
-	    	}
85
-    		string2=this.getRSReceived().getString(3).split(" ");
86
-    		date2.set(Integer.valueOf(string2[0]), Integer.valueOf(string2[1]), Integer.valueOf(string2[2]),Integer.valueOf(string2[3]), Integer.valueOf(string2[4]), Integer.valueOf(string2[5]));
87
-
88
-	    	if (date1.compareTo(date2)>=0) {
89
-	    		message=message+this.getRSReceived().getString(2);
90
-	    		message=message+this.getRSSent().getString(2);
91
-	    	}else {
92
-	    		message=message+this.getRSSent().getString(2);
93
-	    		message=message+this.getRSReceived().getString(2);
94
-	    	}
95
-    		encore1=this.getRSSent().next();
96
-	    	encore2=this.getRSReceived().next();
97
-
98
-	    }
99
-		
100
-		return message;
101
-	}
102
-	
103
-	public void close_all() throws SQLException {
104
-		this.rs_received.close();
105
-		this.rs_sent.close();
106
-		this.bdd.close();
107
-	}
108
-	//MAIN
109
-	public void Historique() {
110
-		
111
-		this.bdd=new Database();
112
-		System.out.println("coucoudb");
113
-		
114
-		
115
-	}
116
-	
117
-	
118
-}

+ 0
- 124
Application/Clavardage/src/Interface.java View File

@@ -1,124 +0,0 @@
1
-import javax.swing.*;
2
-import java.awt.*;
3
-import java.awt.event.*;
4
-
5
-public class Interface implements ActionListener {
6
-	
7
- private String Pseudolabeltext = "";
8
- final JLabel Pseudolabel = new JLabel("Pseudo: " + Pseudolabeltext);
9
- private JTextField PseudotextField;
10
- private JButton convertPseudo;
11
-
12
- //Specifies the look and feel to use. Valid values:
13
- //null (use the default), "Metal", "System", "Motif", "GTK+"
14
- final static String LOOKANDFEEL = null;
15
-
16
- public Component createComponents() {
17
-	 PseudotextField = new JTextField();
18
-	 PseudotextField.setColumns(10);
19
-	 PseudotextField.setText("Enter pseudo");
20
-	 
21
-	 convertPseudo = new JButton("Convert Pseudo");
22
-	 convertPseudo.addActionListener(this);
23
-	 
24
-	 Pseudolabel.setLabelFor(PseudotextField);
25
-	
26
-	 /*
27
-	 * An easy way to put space between a top-level container
28
-	 * and its contents is to put the contents in a JPanel
29
-	 * that has an "empty" border.
30
-	 */
31
-	 JPanel pane = new JPanel(new GridLayout(0, 1));
32
-	 pane.add(PseudotextField);
33
-	 pane.add(Pseudolabel);
34
-	 pane.add(convertPseudo);
35
-	 pane.setBorder(BorderFactory.createEmptyBorder(
36
-	 30, //top
37
-	 30, //left
38
-	 10, //bottom
39
-	 30) //right
40
-	 );
41
-	
42
-	 return pane;
43
- }
44
- 
45
- // Modify the event handler code depending on which button is pressed.
46
- // If the 1st button is pressed, increase the numClicks value by 1, else
47
- // increase the value by 1000.
48
- public void actionPerformed(ActionEvent e) {
49
-	    String texteUtilisateur = PseudotextField.getText();
50
-	    Pseudolabel.setText("Pseudo: " + texteUtilisateur);
51
- }
52
- 
53
- private static void initLookAndFeel() {
54
-	
55
-	 // Swing allows you to specify which look and feel your program uses-
56
-	 // -Java,
57
-	 // GTK+, Windows, and so on as shown below.
58
-	 String lookAndFeel = null;
59
-	
60
-	 if (LOOKANDFEEL != null) {
61
-		 if (LOOKANDFEEL.equals("Metal")) {
62
-			 lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
63
-		 } else if (LOOKANDFEEL.equals("System")) {
64
-			 lookAndFeel = UIManager.getSystemLookAndFeelClassName();
65
-		 } else if (LOOKANDFEEL.equals("Motif")) {
66
-			 lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
67
-		 } else if (LOOKANDFEEL.equals("GTK+")) { //new in 1.4.2
68
-			 lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
69
-		 } else {
70
-			 System.err.println("Unexpected value of LOOKANDFEEL specified: " + LOOKANDFEEL);
71
-			 lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
72
-		 }
73
-		
74
-		 try {UIManager.setLookAndFeel(lookAndFeel);
75
-		 } catch (ClassNotFoundException e) {
76
-			 System.err.println("Couldn't find class for specified look and feel:" + lookAndFeel);
77
-			 System.err.println("Did you include the L&F library in the class path?");
78
-			 System.err.println("Using the default look and feel.");
79
-		 } catch (UnsupportedLookAndFeelException e) {
80
-			 System.err.println("Can't use the specified look and feel (" + lookAndFeel+ ") on this platform.");
81
-			 System.err.println("Using the default look and feel.");
82
-		 } catch (Exception e) {
83
-			 System.err.println("Couldn't get specified look and feel (" + lookAndFeel + "), for some reason.");
84
-			 System.err.println("Using the default look and feel.");
85
-			 e.printStackTrace();
86
-		 }
87
-	 }
88
- }
89
-
90
- /**
91
- * Create the GUI and show it. For thread safety,
92
- * this method should be invoked from the
93
- * event-dispatching thread.
94
- */
95
- private static void createAndShowGUI() {
96
-	 //Set the look and feel.
97
-	 initLookAndFeel();
98
-	
99
-	 //Make sure we have nice window decorations.
100
-	 JFrame.setDefaultLookAndFeelDecorated(true);
101
-	
102
-	 //Create and set up the window.
103
-	 JFrame frame = new JFrame("SwingApplication");
104
-	 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
105
-	
106
-	 Interface app = new Interface();
107
-	 Component contents = app.createComponents();
108
-	 frame.getContentPane().add(contents, BorderLayout.CENTER);
109
-	
110
-	 //Display the window.
111
-	 frame.pack();
112
-	 frame.setVisible(true);
113
-	 }
114
-	
115
-	 public static void main(String[] args) {
116
-	 //Schedule a job for the event-dispatching thread:
117
-	 //creating and showing this application’s GUI.
118
-	 javax.swing.SwingUtilities.invokeLater(new Runnable() {
119
-		 public void run() {
120
-			 createAndShowGUI();
121
-		 }
122
-	 	});
123
-	 }
124
-}

+ 0
- 67
Application/Clavardage/src/RemoteUser.java View File

@@ -1,67 +0,0 @@
1
-import java.net.InetAddress;
2
-
3
-public class RemoteUser {
4
-
5
-	InetAddress addIP;
6
-	int portTCP;
7
-	String pseudo;
8
-	
9
-	/*** CONSTRUCTOR of RemoteUser ***/
10
-	public RemoteUser(InetAddress remoteUserIP, int remoteUserPortTCP,String pseudo) {
11
-		this.addIP=remoteUserIP;
12
-		this.portTCP=remoteUserPortTCP;
13
-		this.pseudo=pseudo;
14
-	}
15
-	
16
-	/*** GETTERS ***/
17
-	public InetAddress getRemoteUserIP() {
18
-		return addIP;
19
-	}
20
-	public int getRemoteUserPort() {
21
-		return portTCP;
22
-	}
23
-	public String getPseudo() {
24
-		return pseudo;
25
-	}
26
-	
27
-	
28
-	/*** SETTERS ***/
29
-	public void setRemoteUserIP(InetAddress remoteUserIP) {
30
-		this.addIP = remoteUserIP;
31
-	}
32
-	public void setRemoteUserPort(int remoteUserPort) {
33
-		this.portTCP = remoteUserPort;
34
-	}
35
-	public void setRemotePseudo(String remoteUserpseudo) {
36
-		this.pseudo = remoteUserpseudo;
37
-	}
38
-
39
-	/*** OVERRIDE METHODS ***/
40
-	/*
41
-	 * equals
42
-	 * @see java.lang.Object#equals(java.lang.Object)
43
-	 */
44
-	@Override
45
-	public boolean equals(Object obj) {
46
-		if (this == obj)
47
-			return true;
48
-		if (obj == null)
49
-			return false;
50
-		if (getClass() != obj.getClass())
51
-			return false;
52
-		RemoteUser other = (RemoteUser) obj;
53
-		if (addIP == null) {
54
-			if (other.addIP != null)
55
-				return false;
56
-		} else if (!addIP.equals(other.addIP))
57
-			return false;
58
-		if (portTCP != other.portTCP)
59
-			return false;
60
-		return true;
61
-	}
62
-
63
-
64
-	
65
-
66
-	
67
-}

+ 0
- 467
Application/Clavardage/src/User.java View File

@@ -1,467 +0,0 @@
1
-import java.awt.BorderLayout;
2
-import java.awt.Component;
3
-import java.awt.GridLayout;
4
-import java.awt.event.ActionEvent;
5
-import java.awt.event.ActionListener;
6
-import java.io.BufferedReader;
7
-import java.io.IOException;
8
-import java.io.InputStreamReader;
9
-import java.io.PrintWriter;
10
-import java.net.*;
11
-import java.text.DateFormat;
12
-import java.text.SimpleDateFormat;
13
-import java.util.Date;
14
-import javax.swing.JOptionPane;
15
-
16
-import java.util.ArrayList; // import the ArrayList class
17
-
18
-
19
-public class User{
20
-	
21
-	/*** CONSTANTES ***/
22
-	final static int portUDPlistening_remoteUsr2 = 20002; // TO REMOVE when we use broadcast
23
-    final static int portUDPlistening_remoteUsr3 = 20003; // TO REMOVE when we use broadcast
24
-    
25
-	/*** VARIABLES ***/
26
-	protected InetAddress addIP;
27
-	protected String pseudo;
28
-	protected int portUDPsend;
29
-	protected int portUDPlistening;
30
-	protected int portTCP;
31
-	protected boolean actif;
32
-	
33
-	protected ArrayList<RemoteUser> remoteUserList = new ArrayList<RemoteUser>(); // listes des utilisateurs actifs
34
-	protected ArrayList<RemoteUser> userChatList = new ArrayList<RemoteUser>(); // listes des utilisateurs avec qui un chat est actif
35
-
36
-	protected UserListeningThreadUDP threadListeningUDP; // UDP listening thread (pour répondre aux nouveaux utilisateurs)
37
-	protected UserListeningThreadTCP threadListeningTCP; // TCP listening thread (pour commencer une nouvelle conversation)
38
-
39
-	/**
40
-	 *  Constructor of User (local)
41
-	 * $parametres
42
-	 * 		* portUDPsend : int => le numéro de port pour envoyé ces informations lors d'un changements ou d'une nouvelle connexion
43
-	 * 		* portUDPlistening : int => le numéro de port pour recevoir les informations des nouveaux utilisateurs ou les changements
44
-	 * 		* portTCP : int => le numéro de port pour commencer une nouvelle conversation
45
-	 * <p>
46
-	 * 		On récupère l'adresse de la machine, le numéro de port à utiliser, on demande un pseudo à l'utilisateur
47
-	 * 		que l'on vérifie, une fois validé, l'utilisateur devient actif (Début de l'écoute UDP pour les pseudos et notification aux autres utilisateurs actifs)
48
-	 * </p>
49
-	 */
50
-	
51
-	public User(int portUDPsend,int portUDPlistening,int portTCP) throws IOException{
52
-		try
53
-		{
54
-			this.addIP = InetAddress.getLocalHost();
55
-		}
56
-		catch(UnknownHostException e) {
57
-			JOptionPane.showMessageDialog(null ,"Could not find local address!");
58
-		}
59
-		
60
-		this.portUDPsend = portUDPsend;
61
-		this.portUDPlistening = portUDPlistening;
62
-		this.portTCP = portTCP;
63
-		
64
-		this.initPseudo();
65
-		
66
-		this.active();
67
-	}
68
-	
69
-	/**
70
-	 * Constructor of User (simulation of remote user)
71
-	 * $parametres
72
-	 * 		* portUDPsend : int => le numéro de port pour envoyé ces informations lors d'un changements ou d'une nouvelle connexion
73
-	 * 		* portUDPlistening : int => le numéro de port pour recevoir les informations des nouveaux utilisateurs ou les changements
74
-	 * 		* portTCP : int => le numéro de port pour commencer une nouvelle conversation
75
-	 * 		* pseudo : String => le pseudo avec lequel on initie l'utilisateur distant (! pas de vérification)
76
-	 * <p>
77
-	 * 		On récupère l'adresse de la machine, le numéro de port à utiliser, on demande un pseudo à l'utilisateur
78
-	 * 		que l'on vérifie, une fois validé, l'utilisateur devient actif (Début de l'écoute UDP pour les pseudos 
79
-	 * 		et notification aux autres utilisateurs actifs)
80
-	 * </p>
81
-	 */
82
-	public User(int portUDPsend,int portUDPlistening, int portTCP,String pseudo) {
83
-		try
84
-		{
85
-			this.addIP = InetAddress.getLocalHost();
86
-		}
87
-		catch(UnknownHostException e) {
88
-			JOptionPane.showMessageDialog(null ,"Could not find local address!");
89
-		}
90
-		this.portUDPsend = portUDPsend;
91
-		this.portUDPlistening = portUDPlistening;
92
-		this.portTCP = portTCP;
93
-		this.pseudo = pseudo;
94
-
95
-		this.active();
96
-		
97
-	}
98
-	
99
-	
100
-	/*** GETTERS ***/
101
-	public InetAddress getAddIP() {
102
-		return addIP;
103
-	}
104
-	public String getPseudo() {
105
-		return pseudo;
106
-	}
107
-	public int getPortTCP() {
108
-		return portTCP;
109
-	}
110
-	public int getPortUDPlistening() {
111
-		return portUDPlistening;
112
-	}
113
-	public int getPortUDPsend() {
114
-		return portUDPsend;
115
-	}
116
-	public boolean isActif() {
117
-		return actif;
118
-	}
119
-	
120
-	/*** SETTERS ***/
121
-	public void setAddIP(InetAddress addIP) {
122
-		this.addIP = addIP;
123
-	}
124
-	public void setPortTCP(int portTCP) {
125
-		this.portTCP = portTCP;
126
-	}
127
-	public void setPortUDPlistening(int portUDPlistening) {
128
-		this.portUDPlistening = portUDPlistening;
129
-	}
130
-	public void setPortUDPsend(int portUDPsend) {
131
-		this.portUDPsend = portUDPsend;
132
-	}
133
-	
134
-	/**
135
-	 * <p>
136
-	* 		Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux 
137
-	* 		utilisateurs distants leurs informations.
138
-	* 		On regarde si le pseudo est bien différent de l'ancien
139
-	* </p>
140
-	*/
141
-	private void setPseudo() throws IOException { 
142
-		    String oldPseudo = this.pseudo; //Saves the old one for comparison
143
-
144
-		    String tmpPseudo = JOptionPane.showInputDialog(null, "Enter nickname:");  // Read user input
145
-
146
-		    while(!(this.validatePseudo(tmpPseudo)) || tmpPseudo.equals(oldPseudo)) {
147
-		        tmpPseudo = JOptionPane.showInputDialog(null, "Already exist, enter another nickname :");  // Read user input
148
-		    }
149
-
150
-		    this.pseudo = tmpPseudo;
151
-		    //myObj.close();
152
-		    JOptionPane.showMessageDialog(null ,"Your new nickname : " + tmpPseudo + " is valid !");
153
-
154
-		    notify_remote_user();
155
-		}
156
-
157
-	/**
158
-	 * <p>
159
-	 * 		Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux 
160
-	 * 		utilisateurs distants leurs informations
161
-	 * </p>
162
-	 */
163
-	public void initPseudo() throws IOException {
164
-	    String tmpPseudo = JOptionPane.showInputDialog(null, "Enter nickname:");  // Read user input
165
-
166
-		while(!(this.validatePseudo(tmpPseudo))) { // On demande aux autres utilisateurs de nous envoyer leurs informations et on test si le pseudo est déjà utilisé
167
-		    tmpPseudo = JOptionPane.showInputDialog(null, "Enter another nickname:");  // Read user input
168
-		}
169
-		
170
-		this.pseudo = tmpPseudo;
171
-		//sc1.close();
172
-		JOptionPane.showMessageDialog(null ,"Your nickname : " + tmpPseudo + " is valid !");
173
-	}
174
-	
175
-	public void TCPmessage(int index) throws IOException {
176
-		Socket link=null;
177
-		String s1;
178
-		try {
179
-			link=new Socket(this.userChatList.get(index).addIP,this.userChatList.get(index).portTCP);
180
-
181
-			System.out.println("Server is listening on port"+this.portTCP+"of localhost");
182
-		}catch(IOException e) {
183
-			
184
-			System.out.println("Server is not listening on port"+this.portTCP+" of localhost");
185
-			
186
-		}
187
-		BufferedReader in=null;
188
-		try {
189
-			in = new BufferedReader(new InputStreamReader(link.getInputStream()));
190
-		} catch (IOException e) {
191
-			// TODO Auto-generated catch block
192
-			e.printStackTrace();
193
-		}
194
-		try {
195
-			PrintWriter out = new PrintWriter(link.getOutputStream(),true);
196
-		} catch (IOException e) {
197
-			// TODO Auto-generated catch block
198
-			e.printStackTrace();
199
-		}
200
-		String input;
201
-		String s2 = (this.getPseudo()+" reçoit un message");
202
-		try {
203
-			while (!(input=in.readLine()).equals("end")) {
204
-				System.out.print("client_recoit:"+input);
205
-			}
206
-		} catch (IOException e) {
207
-			// TODO Auto-generated catch block
208
-			e.printStackTrace();
209
-		}
210
-		/*or (int i=0; i<4; i++) {
211
-			System.out.println("client envoie");
212
-			out.println("coucou \n");
213
-		}
214
-		out.println("end");*/
215
-		try {
216
-			link.close();
217
-		} catch (IOException e) {
218
-			// TODO Auto-generated catch block
219
-			e.printStackTrace();
220
-		}
221
-	}
222
-	
223
-	
224
-	/**
225
-	 * <p>
226
-	 * 		*tmpPseudo : String => Le pseudo à valider
227
-	 *</p><p>
228
-	 * 		Envoi en broadcast (pour l'instant envoi sur les ports de notre ordinateur) d'une demande d'information 
229
-	 *</p><p>
230
-	 * 		On attend les réponses pendant 5 secondes
231
-	 *</p><p>
232
-	 * 		On valide le pseudo en fonction des pseudos reçu
233
-	 *</p><p>
234
-	 * 		On en profite pour ajouter les utilisateurs répondant à notre liste d'utilisateur distant (RemoteUser)
235
-	 * </p>
236
-	 */
237
-	public Boolean validatePseudo(String tmpPseudo) throws IOException {
238
-
239
-		
240
-		// Call broadcast 
241
-		InetAddress broadcastIP = InetAddress.getLocalHost(); // change to broadcast
242
-		//System.out.println(broadcastIP);
243
-		DatagramSocket dgramSocket = new DatagramSocket(this.portUDPsend,this.addIP);
244
-		byte[] buffer = new byte[256];
245
-		
246
-		// Création du message à envoyer
247
-		String toSend = this.getAddIP()+":"+this.portUDPsend+":test";
248
-		
249
-		// Send to remote user 1
250
-		DatagramPacket outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, portUDPlistening_remoteUsr2);
251
-		dgramSocket.send(outPacket);
252
-		
253
-		// Send to remote user 2
254
-		outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, portUDPlistening_remoteUsr3);
255
-		dgramSocket.send(outPacket);
256
-		
257
-		// Initialisation des variables de la boucle
258
-		Boolean valid = true;
259
-	
260
-        DatagramPacket inPacket;
261
-        String response = null;
262
-        String[] tabresponse= new String [4];
263
-		dgramSocket.setSoTimeout(1000);
264
-		Boolean arecu;
265
-		
266
-		System.out.print("Wait for pseudo validation ...\n");
267
-
268
-		int nbReponse =0;
269
-		Date oldDate = new Date();
270
-        Date newDate = new Date();
271
-		while( (newDate.getTime()-oldDate.getTime()) < 5000 && valid) {
272
-			
273
-			nbReponse++;
274
-			inPacket= new DatagramPacket(buffer, buffer.length);
275
-			
276
-			arecu=true;
277
-			try{
278
-				dgramSocket.receive(inPacket);
279
-			}catch (Exception e) {
280
-				arecu=false;
281
-			} 
282
-			buffer = inPacket.getData();
283
-			response = new String(buffer);
284
-			
285
-			if(arecu) {				
286
-				// On découpe la réponse en tableau de string ([adresseIP,tcpPort,nickname])
287
-				tabresponse = response.split(":");
288
-				
289
-				// Affichage de la réponse
290
-				System.out.println("Remote user n°"+nbReponse+
291
-													"\nIP : "+tabresponse[0]+
292
-													"\nn°Port : "+tabresponse[1]+
293
-													"\npseudo : "+tabresponse[2]);
294
-				
295
-				// Si reception on ajoute l'utilisateur à notre liste d'utilisateur distant
296
-				this.addRemoteUser(InetAddress.getByName(tabresponse[0].split("/")[1]),Integer.parseInt(tabresponse[1]),tabresponse[2]);
297
-				valid= (tmpPseudo.compareTo(tabresponse[2])!=0); // On regarde la différence entre notre pseudo et le pseudo reçu
298
-				
299
-			}
300
-			
301
-	        newDate = new Date();
302
-		}
303
-		dgramSocket.close();
304
-		
305
-		if(!valid) {
306
-			JOptionPane.showMessageDialog(null ,"Nickname : "+tmpPseudo +" is taken !");
307
-		}
308
-		
309
-		return valid;
310
-	}
311
-
312
-	/**
313
-	 * <p>
314
-	 * 		*remoteUserIP : InetAddress => l'adresse IP de l'utilisateur distant
315
-	 * </p><p>
316
-	 * 		*remoteUserPortTCP : int => le numéro de port TCP d'écoute de l'utilisateur distant
317
-	 * </p><p>
318
-	 * 		*remoteUserPseudo : String => le pseudo de l'utilisateur distant
319
-	 * </p><p>
320
-	 * 		Ajout ou mise à jour l'utilisateur distant dans notre liste d'utilisateur distant
321
-	 * </p>
322
-	 */
323
-	public void addRemoteUser(InetAddress remoteUserIP, int remoteUserPortTCP,String remoteUserPseudo) {
324
-		RemoteUser tmpRemoteUser = new RemoteUser(remoteUserIP,remoteUserPortTCP,remoteUserPseudo);
325
-		int index = this.remoteUserList.indexOf(tmpRemoteUser);
326
-		if(index!=-1) {
327
-			System.out.println("("+this.pseudo+") - "+"MAJ, IP(port) of user : "+remoteUserPseudo+" => "+remoteUserIP+"("+remoteUserPortTCP+")");
328
-			this.remoteUserList.set(index,tmpRemoteUser);
329
-		}
330
-		else {
331
-			System.out.println("("+this.pseudo+") - "+"Add new user IP(port) of user : "+remoteUserPseudo+" => "+remoteUserIP+"("+remoteUserPortTCP+")");
332
-			this.remoteUserList.add(tmpRemoteUser);
333
-		}
334
-	}
335
-	
336
-	/**
337
-	 * <p>
338
-	 * 		En utilisant le port UDP d'envoi, on envoie en broadcast les informations nous concernant
339
-	 * </p>
340
-	 */
341
-	public void notify_remote_user() {
342
-		// Création du socket d'envoi d'information
343
-		DatagramSocket dgramSocket= null;
344
-        try {
345
-            dgramSocket= new DatagramSocket(portUDPsend,this.addIP);
346
-        } catch (IOException e) {
347
-            e.printStackTrace();
348
-        }
349
-
350
-        // Construction du message à envoyer
351
-        String toSend = this.addIP.toString()+":"+this.portTCP+":"+this.pseudo+":test";
352
-        
353
-        DatagramPacket outPacket =null;
354
-        
355
-        // Send information to usr2
356
-        if(this.portUDPlistening!=portUDPlistening_remoteUsr2) {
357
-        	outPacket = new DatagramPacket(toSend.getBytes(), toSend.length(),this.addIP, portUDPlistening_remoteUsr2);
358
-            try {
359
-                dgramSocket.send(outPacket);
360
-            } catch (IOException e) {
361
-                e.printStackTrace();
362
-            }
363
-        }
364
-        
365
-        
366
-        // Send information to usr3
367
-        if(this.portUDPlistening!=portUDPlistening_remoteUsr3) {
368
-
369
-	        outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),this.addIP, portUDPlistening_remoteUsr3);
370
-	        try {
371
-	            dgramSocket.send(outPacket);
372
-	        } catch (IOException e) {
373
-	            e.printStackTrace();
374
-	        }
375
-        }
376
-        dgramSocket.close();
377
-	}
378
-
379
-	/**
380
-	 * <p>
381
-	 * 	On démarre un thread d'écoute UDP pour répondre au nouveaux utilisateurs,
382
-	 * </p><p>
383
-	 * 	On démarre un thread d'écoute TCP pour commencer une conversation avec les utilisateurs actifs,
384
-	 * </p><p>
385
-	 * 	On notifie les utilisateurs distants actifs de notre passage en mode actif (envoi de nos informations)
386
-	 * </p>
387
-	 */
388
-	private void active() {
389
-		this.threadListeningUDP = new UserListeningThreadUDP("UDP Listening thread",this);
390
-		this.threadListeningUDP.start();
391
-		
392
-		this.threadListeningTCP = new UserListeningThreadTCP("TCP main Listening thread",this);
393
-		this.threadListeningTCP.start();
394
-		
395
-		notify_remote_user();
396
-
397
-		this.actif=true;
398
-	}
399
-	
400
-	/**
401
-	 * <p>
402
-	 * Affichage de la liste d'utilisateurs actifs avec leurs index dans la liste
403
-	 * </p>
404
-	 */
405
-	public void printRemoteUserList() {
406
-		System.out.println("Internal list of active remote users:");
407
-		
408
-        for(int i=0; i<this.remoteUserList.size(); i++) {
409
-        	System.out.println("- ("+i+") Username: " + this.remoteUserList.get(i).getPseudo());
410
-        }
411
-    }
412
-	
413
-	/**
414
-	 * <p>
415
-	 * Laisse l'utilisateur choisir parmis la liste d'utilisateurs actifs celui avec lequel il souhaite échanger via un chat
416
-	 *</p> 
417
-	 */
418
-	public void getOneActiveUser() throws IOException {
419
-		this.printRemoteUserList();
420
-        int index=Integer.parseInt(JOptionPane.showInputDialog(null, "Please, enter index of one active user that you saw on the list to start a conversation with:"));
421
-        
422
-        if (index >= 0 && index<remoteUserList.size()) {
423
-            if(userChatList.contains(remoteUserList.get(index))) {
424
-            	JOptionPane.showMessageDialog(null ,"User "+remoteUserList.get(index).getPseudo()+" is already in chat with you");
425
-            }
426
-            else {
427
-                userChatList.add(remoteUserList.get(index));
428
-                JOptionPane.showMessageDialog(null ,"New chat with "+remoteUserList.get(index).getPseudo());
429
-            }
430
-        }
431
-        else {
432
-        	JOptionPane.showMessageDialog(null ,"Wrong index (no active at index number "+index+" )");
433
-        }
434
-        
435
-        this.TCPmessage(index);
436
-        //sc2.close();
437
-    }
438
-	
439
-	public static void main(String[] args) throws IOException, InterruptedException {
440
-			// Création des utilisateurs
441
-			User usr2 = new User(12226,portUDPlistening_remoteUsr2,22222,"Mike");  // simulation d'un utilisateur distant n1
442
-			User usr3 = new User(12224,portUDPlistening_remoteUsr3,22223,"Alice"); // simulation d'un utilisateur distant n2
443
-			User usr1 = new User(12225,20001,22221); // Notre utilisateur local
444
-			
445
-			// Fonction appelé par notre utilisateur local
446
-			usr1.getOneActiveUser();
447
-			usr1.setPseudo();
448
-			
449
-			// On attends 5 secondes
450
-			System.out.println("Sleep mode for 5 seconds");
451
-			Thread.sleep(5000);
452
-			// On ferme les différents threads et socket d'écoute
453
-			
454
-			
455
-			
456
-		    usr1.threadListeningUDP.close();
457
-		    usr2.threadListeningUDP.close();
458
-		    usr3.threadListeningUDP.close();
459
-		    
460
-		    usr1.threadListeningTCP.close();
461
-		    usr2.threadListeningTCP.close();
462
-		    usr3.threadListeningTCP.close();
463
-		    JOptionPane.showMessageDialog(null ,"End");
464
-
465
-		    
466
-	}
467
-}

+ 0
- 55
Application/Clavardage/src/UserConnexionthreadTCP.java View File

@@ -1,55 +0,0 @@
1
-import java.io.BufferedReader;
2
-import java.io.IOException;
3
-import java.io.InputStreamReader;
4
-import java.io.PrintWriter;
5
-import java.net.DatagramSocket;
6
-import java.net.Socket;
7
-import java.text.DateFormat;
8
-import java.text.SimpleDateFormat;
9
-import java.util.Date;
10
-
11
-public class UserConnexionthreadTCP extends Thread{
12
-	private User myUser;
13
-	private Socket socket;
14
-	
15
-	public UserConnexionthreadTCP(String s,User user,Socket socket) { 
16
-		super(s);
17
-		this.myUser = user;
18
-		this.socket=socket;
19
-		
20
-	}
21
-	
22
-	public void run() {
23
-		Socket link = this.socket;
24
-		try {
25
-			BufferedReader in =new BufferedReader(new InputStreamReader(link.getInputStream()));
26
-		} catch (IOException e) {
27
-			// TODO Auto-generated catch block
28
-			e.printStackTrace();
29
-		}
30
-		PrintWriter out=null;
31
-		try {
32
-			out = new PrintWriter(link.getOutputStream(),true);
33
-		} catch (IOException e) {
34
-			// TODO Auto-generated catch block
35
-			e.printStackTrace();
36
-		}
37
-		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
38
-		Date date = new Date();
39
-		System.out.println(myUser.getPseudo()+" envoie un message");
40
-		out.println(dateFormat.format(date));
41
-		out.println("end");
42
-		String input;
43
-		/*while (!(input=in.readLine()).equals("end")) {
44
-			System.out.print("server_recoit:"+input);
45
-		}*/
46
-		try {
47
-			link.close();
48
-		} catch (IOException e) {
49
-			// TODO Auto-generated catch block
50
-			e.printStackTrace();
51
-		}		
52
-	}
53
-	
54
-
55
-}

+ 0
- 95
Application/Clavardage/src/UserListeningThreadTCP.java View File

@@ -1,95 +0,0 @@
1
-import java.io.BufferedReader;
2
-import java.io.IOException;
3
-import java.io.InputStreamReader;
4
-import java.io.PrintWriter;
5
-import java.net.DatagramPacket;
6
-import java.net.DatagramSocket;
7
-import java.net.InetAddress;
8
-import java.net.ServerSocket;
9
-import java.net.Socket;
10
-import java.net.UnknownHostException;
11
-import java.text.DateFormat;
12
-import java.text.SimpleDateFormat;
13
-import java.util.Date;
14
-
15
-public class UserListeningThreadTCP extends Thread{
16
-	
17
-	private User myUser;
18
-	//private DatagramSocket dgramSocket=null;
19
-	
20
-	/* CONSTRUCTOR OF UserListeningThreadTCP
21
-	 * $parametres 
22
-	 * 		* s : String => nom du thread
23
-	 * 		* user : User => utilisateur utilisant ce thread
24
-	 * $description
25
-	 * 		Création d'un socket d'écoute
26
-	 */
27
-	public UserListeningThreadTCP(String s,User user) { 
28
-		super(s);
29
-		this.myUser = user;
30
-	/*	try {
31
-			this.dgramSocket = new DatagramSocket(this.myUser.getPortTCP(),this.myUser.getAddIP());
32
-		} catch (IOException e) {
33
-			e.printStackTrace();
34
-		}
35
-		
36
-		*/
37
-		
38
-	}
39
-	
40
-	public void accept(ServerSocket servSocket) throws IOException {
41
-		Socket socket_tcp= servSocket.accept();
42
-		UserConnexionthreadTCP threadtcp= new UserConnexionthreadTCP("Chat_with_"+myUser.getPseudo(),myUser,socket_tcp);
43
-		threadtcp.start();
44
-		threadtcp.interrupt();
45
-		
46
-		
47
-	}
48
-	
49
-	/* run
50
-	 * $description
51
-	 * 		écoutes les messages TCP tant que l'utilisateur est actif
52
-	 * 		Traitement
53
-	 * 			Si réception d'une demande, créer un
54
-	 */
55
-	public void run(){ 
56
-		
57
-		// Tant que l'utilisateur est actif on attends la demande de nouvelle conversation
58
-		while(true) {
59
-			
60
-			ServerSocket servSocket=null;
61
-			try {
62
-				servSocket = new ServerSocket(myUser.portTCP);
63
-			} catch (IOException e) {
64
-				// TODO Auto-generated catch block
65
-				e.printStackTrace();
66
-			}
67
-			
68
-			try {
69
-				this.accept(servSocket);
70
-			} catch (IOException e) {
71
-				// TODO Auto-generated catch block
72
-				e.printStackTrace();
73
-			}
74
-				
75
-			
76
-		}	
77
-		
78
-	}
79
-	
80
-	/* close
81
-	 * $description
82
-	 * 		ferme le socket d'écoute UDP
83
-	 * 		interrupt UDP listening threadS
84
-	 */
85
-	public void close() {
86
-	//	this.dgramSocket.close();
87
-		System.out.println("End of listing thread TCP ("+this.myUser.getPseudo()+")");
88
-		try {
89
-			this.interrupt();
90
-		}catch (Exception e){
91
-			e.printStackTrace();
92
-		}
93
-	}
94
-	
95
-}

+ 0
- 114
Application/Clavardage/src/UserListeningThreadUDP.java View File

@@ -1,114 +0,0 @@
1
-import java.io.IOException;
2
-import java.net.DatagramPacket;
3
-import java.net.DatagramSocket;
4
-import java.net.InetAddress;
5
-import java.net.UnknownHostException;
6
-
7
-public class UserListeningThreadUDP extends Thread{
8
-	
9
-	private User myUser;
10
-	private DatagramSocket dgramSocket=null;
11
-	
12
-	/* CONSTRUCTOR OF UserListeningThreadUDP
13
-	 * $parametres 
14
-	 * 		* s : String => nom du thread
15
-	 * 		* user : User => utilisateur utilisant ce thread
16
-	 * $description
17
-	 * 		Création d'un socket d'écoute
18
-	 */
19
-	public UserListeningThreadUDP(String s,User user) { 
20
-		super(s);
21
-		this.myUser = user;
22
-		try {
23
-			this.dgramSocket = new DatagramSocket(this.myUser.getPortUDPlistening(),this.myUser.getAddIP());
24
-		} catch (IOException e) {
25
-			e.printStackTrace();
26
-		}	
27
-	}
28
-	
29
-	/* run
30
-	 * $description
31
-	 * 		écoutes les messages UDP tant que l'utilisateur est actif
32
-	 * 		Traitement
33
-	 * 			1) Si demande d'information => envoi ses informations
34
-	 * 			2) Si réception d'information => ajoute les informations
35
-	 */
36
-	public void run(){ 
37
-		
38
-		// Tant que l'utilisateur est actif on attends les messages des nouveaux utilisateurs et changements des utilisateurs actifs 
39
-		while(true) {
40
-
41
-			// Réception du message
42
-			byte[] buffer = new byte[256];
43
-			DatagramPacket inPacket= new DatagramPacket(buffer, buffer.length);
44
-			try {
45
-				dgramSocket.receive(inPacket);
46
-			} catch (Exception e) {
47
-				e.printStackTrace();
48
-			}
49
-			buffer = inPacket.getData();
50
-
51
-			// Traitement en fonction du message reçu
52
-			String receiveMsg = new String(buffer);
53
-			String [] tabMsg = receiveMsg.split(":");
54
-			
55
-			
56
-			// si demande d'information d'un nouvel utilisateur
57
-			if(tabMsg.length==3) { 
58
-				InetAddress itsIP = null;
59
-				try {
60
-					itsIP = InetAddress.getByName(tabMsg[0].split("/")[1]); // On récupère l'adresse IP de l'utilisateur distant
61
-				} catch (UnknownHostException e1) {
62
-					// TODO Auto-generated catch block
63
-					e1.printStackTrace();
64
-				}
65
-				int senderUDPport = Integer.parseInt(tabMsg[1]); // On récupère le port UDP de l'utilisateur distant
66
-				
67
-				String toSend = myUser.getAddIP().toString()+":"+myUser.getPortTCP()+":"+myUser.getPseudo()+":test";
68
-				DatagramPacket outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),itsIP, senderUDPport);
69
-
70
-				try {
71
-					dgramSocket.send(outPacket);
72
-				} catch (IOException e) {
73
-					e.printStackTrace();
74
-				}
75
-			}
76
-			
77
-			// Si un nouvel utilisateur passe en mode actif ou changement d'information
78
-			else { 
79
-				try {
80
-					// On récupère l'adresse IP et le port TCP de l'utilisateur distant et ajout à la liste de l'utilisateur utilisant ce thread 
81
-					this.myUser.addRemoteUser(InetAddress.getByName(tabMsg[0].split("/")[1]),Integer.parseInt(tabMsg[1]),tabMsg[2]);
82
-				} catch (NumberFormatException e) {
83
-					// TODO Auto-generated catch block
84
-					e.printStackTrace();
85
-				} catch (UnknownHostException e) {
86
-					// TODO Auto-generated catch block
87
-					e.printStackTrace();
88
-				}
89
-			}
90
-			
91
-			
92
-		}
93
-		
94
-
95
-	}
96
-	
97
-	/* close
98
-	 * $description
99
-	 * 		ferme le socket d'écoute UDP
100
-	 * 		interrupt UDP listening threadS
101
-	 */
102
-	public void close() {
103
-		this.dgramSocket.close();
104
-		System.out.println("End of listing thread UDP ("+this.myUser.getPseudo()+")");
105
-		try {
106
-			this.interrupt();
107
-		}catch (Exception e){
108
-			e.printStackTrace();
109
-		}
110
-	}
111
-}
112
-
113
-
114
-

+ 4
- 0
Application/Clavardage/src/model/Chat.java View File

@@ -8,6 +8,7 @@ public class Chat {
8 8
 	private int localUser_portTCP;
9 9
 	private int remoteUser_portTCP;
10 10
 	private ArrayList<RemoteUser> remoteUsersChatList = new ArrayList<RemoteUser>(); // listes des utilisateurs sur ce chat
11
+	private ArrayList<Message> messages = new ArrayList<Message>();
11 12
 
12 13
 	/**
13 14
 	 *  Constructor of Chat (local)
@@ -36,6 +37,9 @@ public class Chat {
36 37
 	public ArrayList<RemoteUser> getRemoteUsersChatList() {
37 38
 		return remoteUsersChatList;
38 39
 	}
40
+	public ArrayList<Message> getMessages() {
41
+		return messages;
42
+	}
39 43
 
40 44
 	/*** SETTERS ***/
41 45
 	public void setLocalUser_portTCP(int localUser_portTCP) {

+ 18
- 0
Application/Clavardage/src/model/User.java View File

@@ -4,6 +4,24 @@ import java.net.*;
4 4
 
5 5
 public abstract class User {
6 6
 	
7
+	@Override
8
+	public boolean equals(Object obj) {
9
+		if (this == obj)
10
+			return true;
11
+		if (obj == null)
12
+			return false;
13
+		if (getClass() != obj.getClass())
14
+			return false;
15
+		User other = (User) obj;
16
+		if (addIP == null) {
17
+			if (other.addIP != null)
18
+				return false;
19
+		} else if (!addIP.equals(other.addIP))
20
+			return false;
21
+		if (portTCP != other.portTCP)
22
+			return false;
23
+		return true;
24
+	}
7 25
 	/*** ATTRIBUTS ***/
8 26
 	protected String pseudo;
9 27
 	protected InetAddress addIP;

Loading…
Cancel
Save