Browse Source

Ajout d'une fonction simulant le broadcast + new comments + fix

Alexandre Gonzalvez 3 years ago
parent
commit
09dce244b5
1 changed files with 115 additions and 166 deletions
  1. 115
    166
      Application/Clavardage/src/controller/Controller.java

+ 115
- 166
Application/Clavardage/src/controller/Controller.java View File

@@ -31,10 +31,11 @@ public class Controller {
31 31
 	int NB_SECOND_WAITING_RESPONSE_BROADCAST = 2;
32 32
 	
33 33
 	// TO REMOVE when we use broadcast
34
-	final static int portUDPlistening_usr1 = 31001; 
34
+	final static int portUDPlistening_remoteUsr1 = 31001; 
35 35
 	final static int portUDPlistening_remoteUsr2 = 31002; 
36 36
     final static int portUDPlistening_remoteUsr3 = 31003; 
37
-    final static int [] tabBroadcast = {portUDPlistening_usr1,portUDPlistening_remoteUsr2,portUDPlistening_remoteUsr3};
37
+	final static int portUDPlistening_local = 31004;
38
+    final static int [] tabBroadcast = {portUDPlistening_remoteUsr1,portUDPlistening_remoteUsr2,portUDPlistening_remoteUsr3,portUDPlistening_local};
38 39
     		
39 40
     public Boolean interfaceRunning = false;
40 41
 	/*** ATTRIBUTS ***/
@@ -51,6 +52,7 @@ public class Controller {
51 52
 	 * 		@param portUDPsend : int => le numéro de port pour envoyé ces informations lors d'un changements ou d'une nouvelle connexion
52 53
 	 * 		@param portUDPlistening : int => le numéro de port pour recevoir les informations des nouveaux utilisateurs ou les changements
53 54
 	 * 		@param portTCP : int => le numéro de port pour commencer une nouvelle conversation
55
+	 * @throws IOException 
54 56
 	 * @descrition
55 57
 	 * <p>
56 58
 	 * 		On récupère l'adresse de la machine, on demande un pseudo à l'utilisateur que l'on vérifie
@@ -60,9 +62,10 @@ public class Controller {
60 62
 	 * 		    - notification aux autres utilisateurs actifs
61 63
 	 * </p>
62 64
 	 */
63
-	private Controller(int portUDPsend,int portUDPlistening,int portTCP,Historique histoire) {
65
+	private Controller(int portUDPsend,int portUDPlistening,int portTCP,Historique histoire) throws IOException {
64 66
 		this.histoire= histoire;
65 67
 		
68
+		// Récupération de l'adresse IP local
66 69
 		InetAddress addIP = null;
67 70
 		try
68 71
 		{
@@ -71,22 +74,26 @@ public class Controller {
71 74
 		catch(UnknownHostException e) {
72 75
 			JOptionPane.showMessageDialog(null ,"Could not find local address!");
73 76
 		}
77
+		
78
+		// Création de l'utilisateur
74 79
 		this.myUser = new LocalUser("Unknown",addIP,portUDPsend,portUDPlistening,portTCP);
75 80
 
76 81
 		try {
77
-			this.myUser.setPseudo(this.initPseudo());
82
+			this.myUser.setPseudo(this.initPseudo()); // Initialisation du pseudo manuel
78 83
 		} catch (IOException e) {
79 84
 			e.printStackTrace();
80 85
 		}
81 86
 		
87
+		// Création des threads d'écoutes
82 88
 		this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this);
83 89
 		this.udp_connect_thread.start();
84
-		
85 90
 		this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this);
86 91
 		this.tcp_connect_thread.start();
87 92
 		
93
+		// Notification des utilisateurs distants
88 94
 		notify_remote_users();
89 95
 		
96
+		// Création de l'interface
90 97
 		interfaceRunning =true;
91 98
 		view=Interface.createAndShowGUI(this);
92 99
 	}
@@ -106,8 +113,11 @@ public class Controller {
106 113
 	 * 		    - notification aux autres utilisateurs actifs
107 114
 	 * </p>
108 115
 	 */
109
-	private Controller(int portUDPsend,int portUDPlistening,int portTCP,String pseudo,Historique histoire) {
116
+	private Controller(int portUDPsend,int portUDPlistening,int portTCP,String pseudo,Historique histoire) throws IOException{
117
+		
110 118
 		this.histoire=histoire;
119
+		
120
+		// Récupération de l'adresse IP local
111 121
 		InetAddress addIP = null;
112 122
 		try
113 123
 		{
@@ -117,6 +127,7 @@ public class Controller {
117 127
 			JOptionPane.showMessageDialog(null ,"Could not find local address!");
118 128
 		}
119 129
 		
130
+		// Création de l'utilisateur
120 131
 		this.myUser = new LocalUser(pseudo,addIP,portUDPsend,portUDPlistening,portTCP);
121 132
 		try {
122 133
 			if(this.validatePseudo(pseudo)) {
@@ -128,6 +139,11 @@ public class Controller {
128 139
 				this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this);
129 140
 				this.tcp_connect_thread.start();
130 141
 				
142
+				
143
+				// Notification des utilisateurs distants
144
+				notify_remote_users();
145
+				
146
+				// Création de l'interface
131 147
 				interfaceRunning =true;
132 148
 				view=Interface.createAndShowGUI(this);
133 149
 			}
@@ -137,54 +153,14 @@ public class Controller {
137 153
 		} catch (IOException e) {
138 154
 			e.printStackTrace();
139 155
 		}
140
-		
141
-		
142
-		
143
-		
144
-		
145
-		
146
-		notify_remote_users();
147 156
 	}
148 157
 	
149 158
 	
150 159
 	
151 160
 	
152
-	/*** GETTERS ***/
153
-	public LocalUser getMyUser() {
154
-		return myUser;
155
-	}
156
-	public Interface getview() {
157
-		return view;
158
-	}
159
-	public ListeningThreadUDP getUdp_connect_thread() {
160
-		return udp_connect_thread;
161
-	}
162
-	public ListeningThreadTCPConnection getTcp_connect_thread() {
163
-		return tcp_connect_thread;
164
-	}
165
-	public Historique getHistory() {
166
-		return histoire;
167
-	}
161
+	/**************************** Initialisation pseudo et découverte utilisateur distant (+notification utilisateurs distants) **********************************/
168 162
 	
169
-	/*** SETTERS ***/
170
-	public void setMyUser(LocalUser myUser) {
171
-		this.myUser = myUser;
172
-	}
173
-	public void setview(Interface view) {
174
-		this.view = view;
175
-	}
176
-	public void setUdp_connect_thread(ListeningThreadUDP udp_connect_thread) {
177
-		this.udp_connect_thread = udp_connect_thread;
178
-	}
179
-	public void setTcp_connect_thread(ListeningThreadTCPConnection tcp_connect_thread) {
180
-		this.tcp_connect_thread = tcp_connect_thread;
181
-	}
182
-	public void setHistory(Historique histoire) {
183
-		this.histoire=histoire;
184
-	}
185
-	
186
-	
187
-	/**
163
+	/** initPseudo
188 164
 	 * <p>
189 165
 	 * 		Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux 
190 166
 	 * 		utilisateurs distants leurs informations
@@ -203,7 +179,7 @@ public class Controller {
203 179
 		return tmpPseudo;
204 180
 	}
205 181
 	
206
-	/**
182
+	/** changePseudo
207 183
 	 * <p>
208 184
 	* 		Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux 
209 185
 	* 		utilisateurs distants leurs informations.
@@ -223,12 +199,11 @@ public class Controller {
223 199
 		    this.myUser.setPseudo(tmpPseudo);
224 200
 		    JOptionPane.showMessageDialog(null ,"Your new nickname : " + tmpPseudo + " is valid !");
225 201
 		    this.notify_remote_users();
226
-
227 202
 	    }
228
-
229
-
230 203
 	}
231
-	/**
204
+	
205
+	
206
+	/** validatePseudo
232 207
 	 * <p>
233 208
 	 * 		*tmpPseudo : String => Le pseudo à valider
234 209
 	 *</p><p>
@@ -242,29 +217,18 @@ public class Controller {
242 217
 	 * </p>
243 218
 	 */
244 219
 	public Boolean validatePseudo(String tmpPseudo) throws IOException {
220
+		Boolean valid = true;
245 221
 
246
-		
247
-		// Call broadcast 
248
-		InetAddress broadcastIP = InetAddress.getLocalHost(); // change to broadcast
249
-		//System.out.println(this.myUser.getPortUDPsend());
250 222
 		DatagramSocket dgramSocket = new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP());
251
-		byte[] buffer = new byte[256];
252 223
 		
253 224
 		// Création du message à envoyer
254 225
 		String toSend = this.myUser.getAddIP()+":"+this.myUser.getPortUDPsend()+":info";
255 226
 		
256
-		// Send to other active user (simulation of broadcast)
257
-		DatagramPacket outPacket = null;
258
-		int tabBroadcastSize = tabBroadcast.length;
259
-		for(int i=0;i<tabBroadcastSize;i++) {
260
-			if(tabBroadcast[i]!=myUser.getPortUDPlistening()) {
261
-				outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, tabBroadcast[i]);
262
-				dgramSocket.send(outPacket);
263
-			}
264
-		}
227
+		// Broadcast du message
228
+		broadcast(dgramSocket,toSend);
265 229
 	
266 230
 		/*** For 5 seconds wait for answer : validate pseudo & add to userlist ***/
267
-		Boolean valid = true;
231
+		byte[] buffer = new byte[256];
268 232
         DatagramPacket inPacket;
269 233
         String response = null;
270 234
         String[] tabresponse= new String [4];
@@ -287,34 +251,53 @@ public class Controller {
287 251
 			
288 252
 			buffer = inPacket.getData();
289 253
 			response = new String(buffer);
290
-			
291 254
 			if(arecu) {				
292 255
 				// On découpe la réponse en tableau de string ([adresseIP,tcpPort,nickname])
293 256
 				tabresponse = response.split(":");
294
-				
295 257
 				// Si reception on ajoute l'utilisateur à notre liste d'utilisateur distant
296 258
 				this.myUser.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
-				
259
+				valid= (tmpPseudo.compareTo(tabresponse[2])!=0); // On regarde la différence entre notre pseudo et le pseudo reçu	
299 260
 			}
300
-			
301 261
 	        newDate = new Date();
302 262
 		}
303
-		dgramSocket.close();
304 263
 		
264
+		
265
+		dgramSocket.close();
305 266
 		if(!valid) {
306 267
 			JOptionPane.showMessageDialog(null ,"Nickname : "+tmpPseudo +" is taken !");
307 268
 		}
308
-		
309 269
 		return valid;
310 270
 	}
311 271
 	
272
+	/***broadcast
273
+	 * 
274
+	 * @param dgramSocket
275
+	 * @param toSend
276
+	 * @param broadcastIP
277
+	 * @throws IOException
278
+	 * <p>
279
+	 * Simulation of broadcast with port given (tabBroadcast)
280
+	 * <p>
281
+	 */
282
+	public void broadcast(DatagramSocket dgramSocket,String toSend) throws IOException {
283
+		InetAddress broadcastIP = InetAddress.getLocalHost(); 
284
+		DatagramPacket outPacket = null;
285
+		int tabBroadcastSize = tabBroadcast.length;
286
+		for(int i=0;i<tabBroadcastSize;i++) {
287
+			if(tabBroadcast[i]!=myUser.getPortUDPlistening()) {
288
+				outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, tabBroadcast[i]);
289
+				dgramSocket.send(outPacket);
290
+			}
291
+		}
292
+	}
293
+	
312 294
 	/** notify_remote_users
313 295
 	 * <p>
314 296
 	 * 		En utilisant le port UDP d'envoi, on envoie en broadcast les informations nous concernant
315 297
 	 * </p>
298
+	 * @throws IOException 
316 299
 	 */
317
-	public void notify_remote_users() {
300
+	public void notify_remote_users() throws IOException {
318 301
 		DatagramSocket dgramSocket= null;
319 302
         try {
320 303
             dgramSocket= new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP());
@@ -324,6 +307,7 @@ public class Controller {
324 307
         
325 308
 		// Send to other active user (simulation of broadcast)
326 309
         String toSend = this.myUser.getAddIP().toString()+":"+this.myUser.getPortTCP()+":"+this.myUser.getPseudo()+":notify";
310
+        /*
327 311
         DatagramPacket outPacket =null;
328 312
         int tabBroadcastSize = tabBroadcast.length;
329 313
 		for(int i=0;i<tabBroadcastSize;i++) {
@@ -336,11 +320,14 @@ public class Controller {
336 320
 	            }
337 321
 			}
338 322
 			
339
-		}
323
+		}*/
324
+        broadcast(dgramSocket,toSend);
340 325
         dgramSocket.close();
341 326
 	}
342 327
 
343 328
 
329
+	/**************************** Gestion des sessions **********************************/
330
+
344 331
 	public Chat openSession(RemoteUser rm) {
345 332
 		Chat c = myUser.addChats(rm); // Create chat and add it to myUser
346 333
 		
@@ -406,6 +393,8 @@ public class Controller {
406 393
 		this.myUser.closeChat(c);
407 394
 	}
408 395
 	
396
+	/**************************** Gestion des messages **********************************/
397
+
409 398
 	public void askToSend(String textMessage){
410 399
 		sendMessage(new Msg_Text(myUser,textMessage), this.activeChat);
411 400
 	}
@@ -449,6 +438,8 @@ public class Controller {
449 438
 		return message;
450 439
 	}
451 440
 	
441
+	/**************************** Autre fonctions **********************************/
442
+
452 443
 	public String [] askUpdateActiveUsers() {
453 444
 		String[] pseudotab = new String[myUser.getRemoteUsersList().size()];
454 445
 		int size = myUser.getRemoteUsersList().size();
@@ -477,70 +468,36 @@ public class Controller {
477 468
 
478 469
 		Historique histoire=new Historique();
479 470
 		
480
-		/*************************       INIT          *******************************/
481 471
 		/** Création des utilisateurs **/
482
-		// LOCAL USER
483
-		Controller ctr1 = new Controller(31011,portUDPlistening_usr1,31021,"Theau",histoire); 
484
-		
485
-		// REMOTEUSER_1 - MIKE
472
+		// REMOTEUSER_1 - THEAU
473
+		Controller ctr1 = new Controller(31011,portUDPlistening_remoteUsr1,31021,"Theau",histoire); 
474
+		// REMOTEUSER_2 - LEONIE
486 475
 		Controller ctr2 = new Controller(31012,portUDPlistening_remoteUsr2,31022,"Leonie",histoire);
487
-		
488
-		// REMOTEUSER_2 - ALICE
476
+		// REMOTEUSER_3 - ALEXANDRE
489 477
 		Controller ctr3 = new Controller(31013,portUDPlistening_remoteUsr3,31023,"Alexandre",histoire); 
490 478
 		
491
-		
492
-		
493
-		
494
-		/*********************** 		TEST AREA  				********************/
495
-		/** Simulation of a session 1 message **/
496
-		/*
497
-		// AFFICHAGE REMOTE USER CHOISIE
498
-		System.out.println("("+ctr1.myUser.getPseudo()+" ) OPEN SESSION WITH "+ctr1.myUser.getRemoteUsersList().get(0).getPseudo());
499
-		// SELECTION DE L UTILISATEUR
500
-		RemoteUser rm0 = ctr1.myUser.getRemoteUsersList().get(0);
501
-		// OPEN SESSION
502
-		ctr1.openSession(rm0); 
503
-		// RECUPERATION DE LA CONVERSATION
504
-		Chat chatwithrm0 = ctr1.myUser.getChats().get(ctr1.myUser.getChatIndexOf(rm0));
505
-		// SEND MESSAGE
506
-		ctr1.sendMessage(new Msg_Text(ctr1.myUser.getAddIP(),"test"), chatwithrm0);
507
-		// CLOSE SESSION
508
-		ctr1.closeSession(chatwithrm0); 
509
-		*/
510
-		
511
-		/** Unused function **/
512
-		// MANUAL SELECTION OF ACTIVE USER
513
-		//ctr1.selectActiveUser(); 
514
-		// CHANGE USER NICKNAME
515
-		//ctr1.changePseudo(); 
516
-					
517
-		
518
-		
519
-		/*************************       LOOP          *******************************/
479
+		// LOCAL USER - AS YOU WANT
480
+		Controller ctr = new Controller(31014,portUDPlistening_local,31024,histoire); 
520 481
 
521
-	
522
-		
523 482
 		/** loop **/
524
-		Boolean running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning;
483
+		Boolean running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning || ctr.interfaceRunning;
525 484
 		while(running) {
526
-			running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning;
485
+			running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning || ctr.interfaceRunning;
527 486
 		}
528 487
 		
529 488
 		System.out.println("Fin de la boucle");
530 489
 		
531 490
 		
532
-		
533
-		/************************ 		 END				*****************************/
534
-		
491
+				
535 492
 		/** Close thread and socket **/
536
-		// REMOTEUSER_1 - MIKE
493
+		// REMOTEUSER_1 - THEAU
494
+		ctr1.close();
495
+		// REMOTEUSER_2 - LEONIE
537 496
 		ctr2.close();
538
-		
539
-		// REMOTEUSER_2 - ALICE
497
+		// REMOTEUSER_3 - ALEXANDRE
540 498
 		ctr3.close();
541
-		
542 499
 		// LOCAL USER
543
-		ctr1.close();
500
+		ctr.close();
544 501
 		
545 502
 		// AFFICHAGE
546 503
 		System.out.println("end program");
@@ -549,48 +506,40 @@ public class Controller {
549 506
 	
550 507
 	
551 508
 	
509
+	/*** GETTERS ***/
510
+	public LocalUser getMyUser() {
511
+		return myUser;
512
+	}
513
+	public Interface getview() {
514
+		return view;
515
+	}
516
+	public ListeningThreadUDP getUdp_connect_thread() {
517
+		return udp_connect_thread;
518
+	}
519
+	public ListeningThreadTCPConnection getTcp_connect_thread() {
520
+		return tcp_connect_thread;
521
+	}
522
+	public Historique getHistory() {
523
+		return histoire;
524
+	}
552 525
 	
526
+	/*** SETTERS ***/
527
+	public void setMyUser(LocalUser myUser) {
528
+		this.myUser = myUser;
529
+	}
530
+	public void setview(Interface view) {
531
+		this.view = view;
532
+	}
533
+	public void setUdp_connect_thread(ListeningThreadUDP udp_connect_thread) {
534
+		this.udp_connect_thread = udp_connect_thread;
535
+	}
536
+	public void setTcp_connect_thread(ListeningThreadTCPConnection tcp_connect_thread) {
537
+		this.tcp_connect_thread = tcp_connect_thread;
538
+	}
539
+	public void setHistory(Historique histoire) {
540
+		this.histoire=histoire;
541
+	}
553 542
 	
554
-	/********************* Fonction debug console => A mettre dans l'interface ******************************************/
555
-	
556
-	/**
557
-	 * <p>
558
-	 * Affichage de la liste d'utilisateurs actifs avec leurs index dans la liste
559
-	 * </p>
560
-	 */
561
-	public void printRemoteUserList() {
562
-		System.out.println("Internal list of active remote users:");
563
-		
564
-        for(int i=0; i<this.myUser.getRemoteUsersList().size(); i++) {
565
-        	System.out.println("- ("+i+") Username: " + this.myUser.getRemoteUsersList().get(i).getPseudo());
566
-        }
567
-    }
568
-	
569
-	/**
570
-	 * <p>
571
-	 * Laisse l'utilisateur choisir parmis la liste d'utilisateurs actifs celui avec lequel il souhaite échanger via un chat
572
-	 *</p> 
573
-	 */
574
-	public void selectActiveUser() throws IOException {
575
-		this.printRemoteUserList();
576
-        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:"));
577
-        
578
-        if (index >= 0 && index<this.myUser.getRemoteUsersList().size()) {
579
-        	
580
-            if(this.myUser.getChatIndexOf(this.myUser.getRemoteUsersList().get(index))==-1){
581
-            	JOptionPane.showMessageDialog(null ,"User "+this.myUser.getRemoteUsersList().get(index).getPseudo()+" is already in chat with you");
582
-            }
583
-            else {
584
-            	this.openSession(myUser.getRemoteUsersList().get(index));
585
-            }
586
-        }
587
-        else {
588
-        	JOptionPane.showMessageDialog(null ,"Wrong index (no active at index number "+index+" )");
589
-        	this.selectActiveUser();
590
-        }
591
-    }
592
-	
593
-	/*************************************************************************************************************************/
543
+}
594 544
 
595 545
 
596
-}

Loading…
Cancel
Save