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

This commit is contained in:
Alexandre Gonzalvez 2021-01-04 12:27:26 +01:00
parent 21eef445a7
commit 09dce244b5

View file

@ -31,10 +31,11 @@ public class Controller {
int NB_SECOND_WAITING_RESPONSE_BROADCAST = 2; int NB_SECOND_WAITING_RESPONSE_BROADCAST = 2;
// TO REMOVE when we use broadcast // TO REMOVE when we use broadcast
final static int portUDPlistening_usr1 = 31001; final static int portUDPlistening_remoteUsr1 = 31001;
final static int portUDPlistening_remoteUsr2 = 31002; final static int portUDPlistening_remoteUsr2 = 31002;
final static int portUDPlistening_remoteUsr3 = 31003; final static int portUDPlistening_remoteUsr3 = 31003;
final static int [] tabBroadcast = {portUDPlistening_usr1,portUDPlistening_remoteUsr2,portUDPlistening_remoteUsr3}; final static int portUDPlistening_local = 31004;
final static int [] tabBroadcast = {portUDPlistening_remoteUsr1,portUDPlistening_remoteUsr2,portUDPlistening_remoteUsr3,portUDPlistening_local};
public Boolean interfaceRunning = false; public Boolean interfaceRunning = false;
/*** ATTRIBUTS ***/ /*** ATTRIBUTS ***/
@ -51,6 +52,7 @@ public class Controller {
* @param portUDPsend : int => le numéro de port pour envoyé ces informations lors d'un changements ou d'une nouvelle connexion * @param portUDPsend : int => le numéro de port pour envoyé ces informations lors d'un changements ou d'une nouvelle connexion
* @param portUDPlistening : int => le numéro de port pour recevoir les informations des nouveaux utilisateurs ou les changements * @param portUDPlistening : int => le numéro de port pour recevoir les informations des nouveaux utilisateurs ou les changements
* @param portTCP : int => le numéro de port pour commencer une nouvelle conversation * @param portTCP : int => le numéro de port pour commencer une nouvelle conversation
* @throws IOException
* @descrition * @descrition
* <p> * <p>
* On récupère l'adresse de la machine, on demande un pseudo à l'utilisateur que l'on vérifie * 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 {
* - notification aux autres utilisateurs actifs * - notification aux autres utilisateurs actifs
* </p> * </p>
*/ */
private Controller(int portUDPsend,int portUDPlistening,int portTCP,Historique histoire) { private Controller(int portUDPsend,int portUDPlistening,int portTCP,Historique histoire) throws IOException {
this.histoire= histoire; this.histoire= histoire;
// Récupération de l'adresse IP local
InetAddress addIP = null; InetAddress addIP = null;
try try
{ {
@ -71,22 +74,26 @@ public class Controller {
catch(UnknownHostException e) { catch(UnknownHostException e) {
JOptionPane.showMessageDialog(null ,"Could not find local address!"); JOptionPane.showMessageDialog(null ,"Could not find local address!");
} }
// Création de l'utilisateur
this.myUser = new LocalUser("Unknown",addIP,portUDPsend,portUDPlistening,portTCP); this.myUser = new LocalUser("Unknown",addIP,portUDPsend,portUDPlistening,portTCP);
try { try {
this.myUser.setPseudo(this.initPseudo()); this.myUser.setPseudo(this.initPseudo()); // Initialisation du pseudo manuel
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
// Création des threads d'écoutes
this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this); this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this);
this.udp_connect_thread.start(); this.udp_connect_thread.start();
this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this); this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this);
this.tcp_connect_thread.start(); this.tcp_connect_thread.start();
// Notification des utilisateurs distants
notify_remote_users(); notify_remote_users();
// Création de l'interface
interfaceRunning =true; interfaceRunning =true;
view=Interface.createAndShowGUI(this); view=Interface.createAndShowGUI(this);
} }
@ -106,8 +113,11 @@ public class Controller {
* - notification aux autres utilisateurs actifs * - notification aux autres utilisateurs actifs
* </p> * </p>
*/ */
private Controller(int portUDPsend,int portUDPlistening,int portTCP,String pseudo,Historique histoire) { private Controller(int portUDPsend,int portUDPlistening,int portTCP,String pseudo,Historique histoire) throws IOException{
this.histoire=histoire; this.histoire=histoire;
// Récupération de l'adresse IP local
InetAddress addIP = null; InetAddress addIP = null;
try try
{ {
@ -117,6 +127,7 @@ public class Controller {
JOptionPane.showMessageDialog(null ,"Could not find local address!"); JOptionPane.showMessageDialog(null ,"Could not find local address!");
} }
// Création de l'utilisateur
this.myUser = new LocalUser(pseudo,addIP,portUDPsend,portUDPlistening,portTCP); this.myUser = new LocalUser(pseudo,addIP,portUDPsend,portUDPlistening,portTCP);
try { try {
if(this.validatePseudo(pseudo)) { if(this.validatePseudo(pseudo)) {
@ -128,6 +139,11 @@ public class Controller {
this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this); this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this);
this.tcp_connect_thread.start(); this.tcp_connect_thread.start();
// Notification des utilisateurs distants
notify_remote_users();
// Création de l'interface
interfaceRunning =true; interfaceRunning =true;
view=Interface.createAndShowGUI(this); view=Interface.createAndShowGUI(this);
} }
@ -137,54 +153,14 @@ public class Controller {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
notify_remote_users();
} }
/*** GETTERS ***/ /**************************** Initialisation pseudo et découverte utilisateur distant (+notification utilisateurs distants) **********************************/
public LocalUser getMyUser() {
return myUser;
}
public Interface getview() {
return view;
}
public ListeningThreadUDP getUdp_connect_thread() {
return udp_connect_thread;
}
public ListeningThreadTCPConnection getTcp_connect_thread() {
return tcp_connect_thread;
}
public Historique getHistory() {
return histoire;
}
/*** SETTERS ***/ /** initPseudo
public void setMyUser(LocalUser myUser) {
this.myUser = myUser;
}
public void setview(Interface view) {
this.view = view;
}
public void setUdp_connect_thread(ListeningThreadUDP udp_connect_thread) {
this.udp_connect_thread = udp_connect_thread;
}
public void setTcp_connect_thread(ListeningThreadTCPConnection tcp_connect_thread) {
this.tcp_connect_thread = tcp_connect_thread;
}
public void setHistory(Historique histoire) {
this.histoire=histoire;
}
/**
* <p> * <p>
* Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux * Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux
* utilisateurs distants leurs informations * utilisateurs distants leurs informations
@ -203,7 +179,7 @@ public class Controller {
return tmpPseudo; return tmpPseudo;
} }
/** /** changePseudo
* <p> * <p>
* Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux * Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux
* utilisateurs distants leurs informations. * utilisateurs distants leurs informations.
@ -223,12 +199,11 @@ public class Controller {
this.myUser.setPseudo(tmpPseudo); this.myUser.setPseudo(tmpPseudo);
JOptionPane.showMessageDialog(null ,"Your new nickname : " + tmpPseudo + " is valid !"); JOptionPane.showMessageDialog(null ,"Your new nickname : " + tmpPseudo + " is valid !");
this.notify_remote_users(); this.notify_remote_users();
} }
} }
/**
/** validatePseudo
* <p> * <p>
* *tmpPseudo : String => Le pseudo à valider * *tmpPseudo : String => Le pseudo à valider
*</p><p> *</p><p>
@ -242,29 +217,18 @@ public class Controller {
* </p> * </p>
*/ */
public Boolean validatePseudo(String tmpPseudo) throws IOException { public Boolean validatePseudo(String tmpPseudo) throws IOException {
Boolean valid = true;
// Call broadcast
InetAddress broadcastIP = InetAddress.getLocalHost(); // change to broadcast
//System.out.println(this.myUser.getPortUDPsend());
DatagramSocket dgramSocket = new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP()); DatagramSocket dgramSocket = new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP());
byte[] buffer = new byte[256];
// Création du message à envoyer // Création du message à envoyer
String toSend = this.myUser.getAddIP()+":"+this.myUser.getPortUDPsend()+":info"; String toSend = this.myUser.getAddIP()+":"+this.myUser.getPortUDPsend()+":info";
// Send to other active user (simulation of broadcast) // Broadcast du message
DatagramPacket outPacket = null; broadcast(dgramSocket,toSend);
int tabBroadcastSize = tabBroadcast.length;
for(int i=0;i<tabBroadcastSize;i++) {
if(tabBroadcast[i]!=myUser.getPortUDPlistening()) {
outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, tabBroadcast[i]);
dgramSocket.send(outPacket);
}
}
/*** For 5 seconds wait for answer : validate pseudo & add to userlist ***/ /*** For 5 seconds wait for answer : validate pseudo & add to userlist ***/
Boolean valid = true; byte[] buffer = new byte[256];
DatagramPacket inPacket; DatagramPacket inPacket;
String response = null; String response = null;
String[] tabresponse= new String [4]; String[] tabresponse= new String [4];
@ -287,34 +251,53 @@ public class Controller {
buffer = inPacket.getData(); buffer = inPacket.getData();
response = new String(buffer); response = new String(buffer);
if(arecu) { if(arecu) {
// On découpe la réponse en tableau de string ([adresseIP,tcpPort,nickname]) // On découpe la réponse en tableau de string ([adresseIP,tcpPort,nickname])
tabresponse = response.split(":"); tabresponse = response.split(":");
// Si reception on ajoute l'utilisateur à notre liste d'utilisateur distant // Si reception on ajoute l'utilisateur à notre liste d'utilisateur distant
this.myUser.addRemoteUser(InetAddress.getByName(tabresponse[0].split("/")[1]),Integer.parseInt(tabresponse[1]),tabresponse[2]); this.myUser.addRemoteUser(InetAddress.getByName(tabresponse[0].split("/")[1]),Integer.parseInt(tabresponse[1]),tabresponse[2]);
valid= (tmpPseudo.compareTo(tabresponse[2])!=0); // On regarde la différence entre notre pseudo et le pseudo reçu valid= (tmpPseudo.compareTo(tabresponse[2])!=0); // On regarde la différence entre notre pseudo et le pseudo reçu
} }
newDate = new Date(); newDate = new Date();
} }
dgramSocket.close();
dgramSocket.close();
if(!valid) { if(!valid) {
JOptionPane.showMessageDialog(null ,"Nickname : "+tmpPseudo +" is taken !"); JOptionPane.showMessageDialog(null ,"Nickname : "+tmpPseudo +" is taken !");
} }
return valid; return valid;
} }
/***broadcast
*
* @param dgramSocket
* @param toSend
* @param broadcastIP
* @throws IOException
* <p>
* Simulation of broadcast with port given (tabBroadcast)
* <p>
*/
public void broadcast(DatagramSocket dgramSocket,String toSend) throws IOException {
InetAddress broadcastIP = InetAddress.getLocalHost();
DatagramPacket outPacket = null;
int tabBroadcastSize = tabBroadcast.length;
for(int i=0;i<tabBroadcastSize;i++) {
if(tabBroadcast[i]!=myUser.getPortUDPlistening()) {
outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, tabBroadcast[i]);
dgramSocket.send(outPacket);
}
}
}
/** notify_remote_users /** notify_remote_users
* <p> * <p>
* En utilisant le port UDP d'envoi, on envoie en broadcast les informations nous concernant * En utilisant le port UDP d'envoi, on envoie en broadcast les informations nous concernant
* </p> * </p>
* @throws IOException
*/ */
public void notify_remote_users() { public void notify_remote_users() throws IOException {
DatagramSocket dgramSocket= null; DatagramSocket dgramSocket= null;
try { try {
dgramSocket= new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP()); dgramSocket= new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP());
@ -324,6 +307,7 @@ public class Controller {
// Send to other active user (simulation of broadcast) // Send to other active user (simulation of broadcast)
String toSend = this.myUser.getAddIP().toString()+":"+this.myUser.getPortTCP()+":"+this.myUser.getPseudo()+":notify"; String toSend = this.myUser.getAddIP().toString()+":"+this.myUser.getPortTCP()+":"+this.myUser.getPseudo()+":notify";
/*
DatagramPacket outPacket =null; DatagramPacket outPacket =null;
int tabBroadcastSize = tabBroadcast.length; int tabBroadcastSize = tabBroadcast.length;
for(int i=0;i<tabBroadcastSize;i++) { for(int i=0;i<tabBroadcastSize;i++) {
@ -336,11 +320,14 @@ public class Controller {
} }
} }
} }*/
broadcast(dgramSocket,toSend);
dgramSocket.close(); dgramSocket.close();
} }
/**************************** Gestion des sessions **********************************/
public Chat openSession(RemoteUser rm) { public Chat openSession(RemoteUser rm) {
Chat c = myUser.addChats(rm); // Create chat and add it to myUser Chat c = myUser.addChats(rm); // Create chat and add it to myUser
@ -406,6 +393,8 @@ public class Controller {
this.myUser.closeChat(c); this.myUser.closeChat(c);
} }
/**************************** Gestion des messages **********************************/
public void askToSend(String textMessage){ public void askToSend(String textMessage){
sendMessage(new Msg_Text(myUser,textMessage), this.activeChat); sendMessage(new Msg_Text(myUser,textMessage), this.activeChat);
} }
@ -449,6 +438,8 @@ public class Controller {
return message; return message;
} }
/**************************** Autre fonctions **********************************/
public String [] askUpdateActiveUsers() { public String [] askUpdateActiveUsers() {
String[] pseudotab = new String[myUser.getRemoteUsersList().size()]; String[] pseudotab = new String[myUser.getRemoteUsersList().size()];
int size = myUser.getRemoteUsersList().size(); int size = myUser.getRemoteUsersList().size();
@ -477,70 +468,36 @@ public class Controller {
Historique histoire=new Historique(); Historique histoire=new Historique();
/************************* INIT *******************************/
/** Création des utilisateurs **/ /** Création des utilisateurs **/
// LOCAL USER // REMOTEUSER_1 - THEAU
Controller ctr1 = new Controller(31011,portUDPlistening_usr1,31021,"Theau",histoire); Controller ctr1 = new Controller(31011,portUDPlistening_remoteUsr1,31021,"Theau",histoire);
// REMOTEUSER_2 - LEONIE
// REMOTEUSER_1 - MIKE
Controller ctr2 = new Controller(31012,portUDPlistening_remoteUsr2,31022,"Leonie",histoire); Controller ctr2 = new Controller(31012,portUDPlistening_remoteUsr2,31022,"Leonie",histoire);
// REMOTEUSER_3 - ALEXANDRE
// REMOTEUSER_2 - ALICE
Controller ctr3 = new Controller(31013,portUDPlistening_remoteUsr3,31023,"Alexandre",histoire); Controller ctr3 = new Controller(31013,portUDPlistening_remoteUsr3,31023,"Alexandre",histoire);
// LOCAL USER - AS YOU WANT
Controller ctr = new Controller(31014,portUDPlistening_local,31024,histoire);
/*********************** TEST AREA ********************/
/** Simulation of a session 1 message **/
/*
// AFFICHAGE REMOTE USER CHOISIE
System.out.println("("+ctr1.myUser.getPseudo()+" ) OPEN SESSION WITH "+ctr1.myUser.getRemoteUsersList().get(0).getPseudo());
// SELECTION DE L UTILISATEUR
RemoteUser rm0 = ctr1.myUser.getRemoteUsersList().get(0);
// OPEN SESSION
ctr1.openSession(rm0);
// RECUPERATION DE LA CONVERSATION
Chat chatwithrm0 = ctr1.myUser.getChats().get(ctr1.myUser.getChatIndexOf(rm0));
// SEND MESSAGE
ctr1.sendMessage(new Msg_Text(ctr1.myUser.getAddIP(),"test"), chatwithrm0);
// CLOSE SESSION
ctr1.closeSession(chatwithrm0);
*/
/** Unused function **/
// MANUAL SELECTION OF ACTIVE USER
//ctr1.selectActiveUser();
// CHANGE USER NICKNAME
//ctr1.changePseudo();
/************************* LOOP *******************************/
/** loop **/ /** loop **/
Boolean running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning; Boolean running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning || ctr.interfaceRunning;
while(running) { while(running) {
running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning; running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning || ctr.interfaceRunning;
} }
System.out.println("Fin de la boucle"); System.out.println("Fin de la boucle");
/************************ END *****************************/
/** Close thread and socket **/ /** Close thread and socket **/
// REMOTEUSER_1 - MIKE // REMOTEUSER_1 - THEAU
ctr2.close();
// REMOTEUSER_2 - ALICE
ctr3.close();
// LOCAL USER
ctr1.close(); ctr1.close();
// REMOTEUSER_2 - LEONIE
ctr2.close();
// REMOTEUSER_3 - ALEXANDRE
ctr3.close();
// LOCAL USER
ctr.close();
// AFFICHAGE // AFFICHAGE
System.out.println("end program"); System.out.println("end program");
@ -549,48 +506,40 @@ public class Controller {
/*** GETTERS ***/
public LocalUser getMyUser() {
return myUser;
}
public Interface getview() {
return view;
}
public ListeningThreadUDP getUdp_connect_thread() {
return udp_connect_thread;
}
public ListeningThreadTCPConnection getTcp_connect_thread() {
return tcp_connect_thread;
}
public Historique getHistory() {
return histoire;
}
/*** SETTERS ***/
public void setMyUser(LocalUser myUser) {
this.myUser = myUser;
}
public void setview(Interface view) {
this.view = view;
}
public void setUdp_connect_thread(ListeningThreadUDP udp_connect_thread) {
this.udp_connect_thread = udp_connect_thread;
}
public void setTcp_connect_thread(ListeningThreadTCPConnection tcp_connect_thread) {
this.tcp_connect_thread = tcp_connect_thread;
}
public void setHistory(Historique histoire) {
this.histoire=histoire;
}
/********************* Fonction debug console => A mettre dans l'interface ******************************************/
/**
* <p>
* Affichage de la liste d'utilisateurs actifs avec leurs index dans la liste
* </p>
*/
public void printRemoteUserList() {
System.out.println("Internal list of active remote users:");
for(int i=0; i<this.myUser.getRemoteUsersList().size(); i++) {
System.out.println("- ("+i+") Username: " + this.myUser.getRemoteUsersList().get(i).getPseudo());
}
}
/**
* <p>
* Laisse l'utilisateur choisir parmis la liste d'utilisateurs actifs celui avec lequel il souhaite échanger via un chat
*</p>
*/
public void selectActiveUser() throws IOException {
this.printRemoteUserList();
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:"));
if (index >= 0 && index<this.myUser.getRemoteUsersList().size()) {
if(this.myUser.getChatIndexOf(this.myUser.getRemoteUsersList().get(index))==-1){
JOptionPane.showMessageDialog(null ,"User "+this.myUser.getRemoteUsersList().get(index).getPseudo()+" is already in chat with you");
}
else {
this.openSession(myUser.getRemoteUsersList().get(index));
}
}
else {
JOptionPane.showMessageDialog(null ,"Wrong index (no active at index number "+index+" )");
this.selectActiveUser();
}
}
/*************************************************************************************************************************/
} }