From 34f15aefd2d225aa4a1c76db078f9909c857765a Mon Sep 17 00:00:00 2001 From: Alexandre Gonzalvez Date: Fri, 8 Jan 2021 21:47:40 +0100 Subject: [PATCH] version_2(broadcast+BD) --- .../Clavardage/src/controller/Controller.java | 180 +++++++++--------- .../Clavardage/src/controller/Historique.java | 140 +++++--------- .../src/controller/ListeningThread.java | 16 -- ...eadTCPChat.java => TListeningTCPChat.java} | 10 +- ...tion.java => TListeningTCPConnection.java} | 11 +- ...eningThreadUDP.java => TListeningUDP.java} | 17 +- Application/Clavardage/src/model/User.java | 29 ++- 7 files changed, 180 insertions(+), 223 deletions(-) delete mode 100644 Application/Clavardage/src/controller/ListeningThread.java rename Application/Clavardage/src/controller/{ListeningThreadTCPChat.java => TListeningTCPChat.java} (94%) rename Application/Clavardage/src/controller/{ListeningThreadTCPConnection.java => TListeningTCPConnection.java} (86%) rename Application/Clavardage/src/controller/{ListeningThreadUDP.java => TListeningUDP.java} (87%) diff --git a/Application/Clavardage/src/controller/Controller.java b/Application/Clavardage/src/controller/Controller.java index 7fefec4..78c1abe 100644 --- a/Application/Clavardage/src/controller/Controller.java +++ b/Application/Clavardage/src/controller/Controller.java @@ -28,7 +28,7 @@ import view.Interface; public class Controller { /*** CONSTANTES ***/ - int NB_SECOND_WAITING_RESPONSE_BROADCAST = 2; + final int NB_SECOND_WAITING_RESPONSE_BROADCAST = 1; // TO REMOVE when we use broadcast final static int portUDPlistening_remoteUsr1 = 31001; @@ -41,15 +41,15 @@ public class Controller { /*** ATTRIBUTS ***/ protected LocalUser myUser; protected Interface view; - private ListeningThreadUDP udp_connect_thread; - private ListeningThreadTCPConnection tcp_connect_thread; + private TListeningUDP udp_connect_thread; + private TListeningTCPConnection tcp_connect_thread; private Historique histoire; protected Chat activeChat; /** * Constructor of Controller * @parametres - * @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 envoyer 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 portTCP : int => le numéro de port pour commencer une nouvelle conversation * @throws IOException @@ -85,9 +85,9 @@ public class Controller { } // Création des threads d'écoutes - this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this); + this.udp_connect_thread = new TListeningUDP("UDP Listening thread",this); this.udp_connect_thread.start(); - this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this); + this.tcp_connect_thread = new TListeningTCPConnection("TCP main Listening thread",this); this.tcp_connect_thread.start(); // Notification des utilisateurs distants @@ -122,6 +122,7 @@ public class Controller { try { addIP = InetAddress.getLocalHost(); + } catch(UnknownHostException e) { JOptionPane.showMessageDialog(null ,"Could not find local address!"); @@ -133,10 +134,10 @@ public class Controller { if(this.validatePseudo(pseudo)) { - this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this); + this.udp_connect_thread = new TListeningUDP("UDP Listening thread",this); this.udp_connect_thread.start(); - this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this); + this.tcp_connect_thread = new TListeningTCPConnection("TCP main Listening thread",this); this.tcp_connect_thread.start(); @@ -156,7 +157,39 @@ public class Controller { } + /*** GETTERS ***/ + public LocalUser getMyUser() { + return myUser; + } + public Interface getview() { + return view; + } + public TListeningUDP getUdp_connect_thread() { + return udp_connect_thread; + } + public TListeningTCPConnection 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(TListeningUDP udp_connect_thread) { + this.udp_connect_thread = udp_connect_thread; + } + public void setTcp_connect_thread(TListeningTCPConnection tcp_connect_thread) { + this.tcp_connect_thread = tcp_connect_thread; + } + public void setHistory(Historique histoire) { + this.histoire=histoire; + } /**************************** Initialisation pseudo et découverte utilisateur distant (+notification utilisateurs distants) **********************************/ @@ -222,7 +255,7 @@ public class Controller { DatagramSocket dgramSocket = new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP()); // Création du message à envoyer - String toSend = this.myUser.getAddIP()+":"+this.myUser.getPortUDPsend()+":info"; + String toSend = this.myUser.getAddIP().getHostAddress()+":"+this.myUser.getPortUDPsend()+":info"; // Broadcast du message broadcast(dgramSocket,toSend); @@ -255,7 +288,7 @@ public class Controller { // On découpe la réponse en tableau de string ([adresseIP,tcpPort,nickname]) tabresponse = response.split(":"); // 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]),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 } newDate = new Date(); @@ -304,23 +337,8 @@ public class Controller { } catch (IOException e) { e.printStackTrace(); } - // Send to other active user (simulation of broadcast) - String toSend = this.myUser.getAddIP().toString()+":"+this.myUser.getPortTCP()+":"+this.myUser.getPseudo()+":notify"; - /* - DatagramPacket outPacket =null; - int tabBroadcastSize = tabBroadcast.length; - for(int i=0;i lstCtr = new ArrayList(); - /** loop **/ - Boolean running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning || ctr.interfaceRunning; + // REMOTE USERS + Controller ctr1 = new Controller(31011,portUDPlistening_remoteUsr1,31021,"Theau",histoire); + lstCtr.add(ctr1); + Controller ctr2 = new Controller(31012,portUDPlistening_remoteUsr2,31022,"Leonie",histoire); + lstCtr.add(ctr2); + Controller ctr3 = new Controller(31013,portUDPlistening_remoteUsr3,31023,"Alexandre",histoire); + lstCtr.add(ctr3); + + // LOCAL USER + Controller ctr = new Controller(31014,portUDPlistening_local,31024,histoire); + lstCtr.add(ctr); + + + /** Loop **/ + Boolean running = isRunning(lstCtr); while(running) { - running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning || ctr.interfaceRunning; + running = isRunning(lstCtr); } - System.out.println("Fin de la boucle"); + System.out.println("Fin de la boucle");//TOREMOVE - - - /** Close thread and socket **/ - // REMOTEUSER_1 - THEAU - ctr1.close(); - // REMOTEUSER_2 - LEONIE - ctr2.close(); - // REMOTEUSER_3 - ALEXANDRE - ctr3.close(); - // LOCAL USER - ctr.close(); - - // AFFICHAGE + /** End - Close thread and socket for every controller**/ + closeThreads(lstCtr); System.out.println("end program"); JOptionPane.showMessageDialog(null ,"END"); } - - - /*** 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; + static boolean isRunning(ArrayList lstCtr){ + boolean isRunning=false; + for(Controller ctr : lstCtr) { + isRunning|=ctr.interfaceRunning; + } + return isRunning; } - /*** 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; + static void closeThreads(ArrayList lstCtr) { + for(Controller ctr : lstCtr) { + ctr.close(); + } } } diff --git a/Application/Clavardage/src/controller/Historique.java b/Application/Clavardage/src/controller/Historique.java index 74b2643..651416e 100644 --- a/Application/Clavardage/src/controller/Historique.java +++ b/Application/Clavardage/src/controller/Historique.java @@ -18,7 +18,7 @@ import model.Msg_Text; public class Historique { - public void saveMessage(model.User ctr1, model.RemoteUser ctr2, String input, String date) { + public void saveMessage(model.User author, model.RemoteUser receiver, String input, String date) { try { Class.forName("java.sql.Driver"); } catch (ClassNotFoundException e) { @@ -46,7 +46,7 @@ public class Historique { // TODO Auto-generated catch block e1.printStackTrace(); } - +/* try { nb_changed_rows = stat.executeUpdate("CREATE TABLE chat ( user_IPcode1 INTEGER, user_IPcode2 INTEGER ,Message VARCHAR(450) ,temps VARCHAR(450) )"); }catch (Exception e) { @@ -54,9 +54,9 @@ public class Historique { } System.out.println("coucou"); - +*/ try { - nb_changed_rows = stat.executeUpdate("INSERT INTO chat VALUES ('"+ctr1.getIPcode()+"','"+ctr2.getIPcode()+"','"+input+"','"+date+"')"); + nb_changed_rows = stat.executeUpdate("INSERT INTO chat VALUES ('"+author.getIPcode()+"','"+receiver.getIPcode()+"','"+input+"','"+date+"')"); } catch (SQLException e) { System.out.println("insertion pas établie"); e.printStackTrace(); @@ -82,106 +82,52 @@ public class Historique { } - public ArrayList retrieveMessage(model.LocalUser user1, model.RemoteUser user2) throws SQLException { - try { - Class.forName("java.sql.Driver"); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + public ArrayList retrieveMessage(model.LocalUser usr, model.RemoteUser rmusr) throws SQLException, ClassNotFoundException { + ArrayList messages=new ArrayList(); + + Class.forName("java.sql.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://srv-bdens.insa-toulouse.fr:3306","tp_servlet_003","povu3Ma2"); Statement stat = null; - try { - stat = con.createStatement(); - } catch (SQLException e2) { - // TODO Auto-generated catch block - e2.printStackTrace(); - } + stat = con.createStatement(); + stat.executeUpdate("USE tp_servlet_003"); +/* Statement stat2 = null; - try { - stat2 = con.createStatement(); - } catch (SQLException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - int nb_changed_rows = stat.executeUpdate("USE tp_servlet_003"); - - try { - nb_changed_rows = stat.executeUpdate("USE TABLE chat ( user_IPcode1 INTEGER, user_IPcode2 INTEGER ,Message VARCHAR(450) ,temps VARCHAR(450) )"); - }catch (Exception e) { - e.printStackTrace(); - - } - nb_changed_rows = stat2.executeUpdate("USE tp_servlet_003"); - - try { - nb_changed_rows = stat2.executeUpdate("USE TABLE chat ( user_IPcode1 INTEGER, user_IPcode2 INTEGER ,Message VARCHAR(450) ,temps VARCHAR(450) )"); - }catch (Exception e) { - e.printStackTrace(); - - } - ResultSet RSSent=(stat.executeQuery("SELECT user_IPcode1, user_IPcode2, Message, temps FROM chat WHERE user_IPcode1="+user1.getIPcode())); - //System.out.println(RSSent); - boolean encore1 = RSSent.next(); - ResultSet RSReceived=(stat2.executeQuery("SELECT user_IPcode1, user_IPcode2, Message, temps FROM chat WHERE user_IPcode1="+user2.getIPcode())); - boolean encore2 = RSReceived.next(); - ArrayList message=new ArrayList(); - //String message=null; - String[] string1=null; - String[] string2=null; - Calendar date1=Calendar.getInstance(); - Calendar date2=Calendar.getInstance(); - while(encore1 || encore2) { - //RSSent=(stat.executeQuery("SELECT user_IPcode1, user_IPcode2, Message, temps FROM chat WHERE user_IPcode1="+user1.getIPcode())); - //boolean temp=RSSent.next(); - - while (RSSent.getInt(2)!=user2.getIPcode()) { - encore1=RSSent.next(); - } - string1=RSSent.getString(4).split(" "); - 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])); - - //RSReceived=(stat.executeQuery("SELECT user_IPcode1, user_IPcode2, Message, temps FROM chat WHERE user_IPcode1="+user2.getIPcode())); - //boolean tempi = RSReceived.next(); - - while (RSReceived.getInt(1)!=user1.getIPcode()) { - encore2=RSReceived.next(); - } - string2=RSReceived.getString(4).split(" "); - 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])); - - if (date1.compareTo(date2)>=0) { - Msg_Text msg =new Msg_Text(user2,RSReceived.getString(4),RSReceived.getString(3)); - message.add(msg); - Msg_Text msg1 =new Msg_Text(user1,RSSent.getString(4),RSSent.getString(3)); - message.add(msg1); - }else { - Msg_Text msg1 =new Msg_Text(user1,RSSent.getString(4),RSSent.getString(3)); - message.add(msg1); - Msg_Text msg =new Msg_Text(user2,RSReceived.getString(4),RSReceived.getString(3)); - message.add(msg); - } - encore1=RSSent.next(); - encore2=RSReceived.next(); - - } - RSSent.close(); - RSReceived.close(); - stat.close(); - stat2.close(); - con.close(); + stat2 = con.createStatement(); + stat.executeUpdate("USE tp_servlet_003"); +*/ - return message; + //int nb_changed_rows; + + String query = "SELECT user_IPcode1 ,Message, temps" + +" FROM chat WHERE (user_IPcode1="+usr.getIPcode() + +" AND user_IPcode2="+rmusr.getIPcode()+") " + +"OR (user_IPcode1="+rmusr.getIPcode()+" " + + "AND user_IPcode2="+usr.getIPcode()+") " + + "ORDER BY temps;"; + ResultSet resultQueryRS=(stat.executeQuery(query)); + + int autorIPcode; + String message; + String strDate; + + boolean encore = resultQueryRS.next(); + while(encore) { + autorIPcode=resultQueryRS.getInt(1); + message=resultQueryRS.getString(2);; + strDate=resultQueryRS.getString(3); + if(usr.getIPcode()==autorIPcode) { + messages.add(new Msg_Text(usr,strDate,message)); + } + else { + messages.add(new Msg_Text(rmusr,strDate,message)); + } + encore=resultQueryRS.next(); + + } + return messages; } -// //MAIN -// public Historique() { -// -// System.out.println("coucoudb"); -// -// -// } } diff --git a/Application/Clavardage/src/controller/ListeningThread.java b/Application/Clavardage/src/controller/ListeningThread.java deleted file mode 100644 index 83f0a80..0000000 --- a/Application/Clavardage/src/controller/ListeningThread.java +++ /dev/null @@ -1,16 +0,0 @@ -package controller; - - -public abstract class ListeningThread extends Thread{ - - protected Controller controller; - - public ListeningThread(String s,Controller controller) { - super(s); - this.controller = controller; - } - - public abstract void run(); - - public abstract void close(); -} diff --git a/Application/Clavardage/src/controller/ListeningThreadTCPChat.java b/Application/Clavardage/src/controller/TListeningTCPChat.java similarity index 94% rename from Application/Clavardage/src/controller/ListeningThreadTCPChat.java rename to Application/Clavardage/src/controller/TListeningTCPChat.java index 8d6ea26..ab8150a 100644 --- a/Application/Clavardage/src/controller/ListeningThreadTCPChat.java +++ b/Application/Clavardage/src/controller/TListeningTCPChat.java @@ -11,8 +11,9 @@ import java.net.Socket; import java.util.Calendar; import java.util.Date; -public class ListeningThreadTCPChat extends ListeningThread{ - +public class TListeningTCPChat extends Thread{ + + protected Controller controller; private Socket socket; /* CONSTRUCTOR OF ListeningThreadTCPConnection @@ -23,10 +24,9 @@ public class ListeningThreadTCPChat extends ListeningThread{ *

*

*/ - public ListeningThreadTCPChat(String s,Controller controller,Socket socket) { - super(s,controller); + public TListeningTCPChat(String s,Controller controller,Socket socket) { + this.controller = controller; this.socket=socket; - // TODO OpenSession si ouverture exterieur } /* run diff --git a/Application/Clavardage/src/controller/ListeningThreadTCPConnection.java b/Application/Clavardage/src/controller/TListeningTCPConnection.java similarity index 86% rename from Application/Clavardage/src/controller/ListeningThreadTCPConnection.java rename to Application/Clavardage/src/controller/TListeningTCPConnection.java index 31833a4..7bbab0a 100644 --- a/Application/Clavardage/src/controller/ListeningThreadTCPConnection.java +++ b/Application/Clavardage/src/controller/TListeningTCPConnection.java @@ -4,10 +4,12 @@ import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; -public class ListeningThreadTCPConnection extends ListeningThread{ +public class TListeningTCPConnection extends Thread{ + protected Controller controller; private Socket socket_tcp=null; private int nbChat = 0; + /* CONSTRUCTOR OF ListeningThreadTCPConnection * @parametres * @param s : String => nom du thread @@ -16,15 +18,14 @@ public class ListeningThreadTCPConnection extends ListeningThread{ *

*

*/ - public ListeningThreadTCPConnection(String s,Controller controller) { - super(s,controller); - + public TListeningTCPConnection(String s,Controller controller) { + this.controller = controller; } public void accept(ServerSocket servSocket) throws IOException { Socket socket_tcp= servSocket.accept(); this.nbChat++; - ListeningThreadTCPChat threadtcpchat = new ListeningThreadTCPChat("Chat_of_"+controller.myUser.getPseudo()+"_"+nbChat,controller,socket_tcp); + TListeningTCPChat threadtcpchat = new TListeningTCPChat("Chat_of_"+controller.myUser.getPseudo()+"_"+nbChat,controller,socket_tcp); threadtcpchat.start(); threadtcpchat.interrupt(); diff --git a/Application/Clavardage/src/controller/ListeningThreadUDP.java b/Application/Clavardage/src/controller/TListeningUDP.java similarity index 87% rename from Application/Clavardage/src/controller/ListeningThreadUDP.java rename to Application/Clavardage/src/controller/TListeningUDP.java index 12d51c3..61dfa06 100644 --- a/Application/Clavardage/src/controller/ListeningThreadUDP.java +++ b/Application/Clavardage/src/controller/TListeningUDP.java @@ -8,10 +8,11 @@ import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; -public class ListeningThreadUDP extends ListeningThread{ +public class TListeningUDP extends Thread{ + protected Controller controller; private DatagramSocket dgramSocket = null; - + /* CONSTRUCTOR OF UserListeningThreadUDP * @parametres @@ -23,13 +24,14 @@ public class ListeningThreadUDP extends ListeningThread{ * Création d'un socket d'écoute UDP *

*/ - public ListeningThreadUDP(String s,Controller controller) { - super(s,controller); + public TListeningUDP(String s,Controller controller) { + this.controller = controller; try { this.dgramSocket = new DatagramSocket(this.controller.myUser.getPortUDPlistening(),this.controller.myUser.getAddIP()); } catch (IOException e) { e.printStackTrace(); } + } /* run @@ -60,19 +62,18 @@ public class ListeningThreadUDP extends ListeningThread{ String receiveMsg = new String(buffer); String [] tabMsg = receiveMsg.split(":"); - // si demande d'information d'un nouvel utilisateur if(tabMsg.length==3) { InetAddress itsIP = null; try { - itsIP = InetAddress.getByName(tabMsg[0].split("/")[1]); // On récupère l'adresse IP de l'utilisateur distant + itsIP = InetAddress.getByName(tabMsg[0]); // On récupère l'adresse IP de l'utilisateur distant } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int senderUDPport = Integer.parseInt(tabMsg[1]); // On récupère le port UDP de l'utilisateur distant - String toSend = controller.myUser.getAddIP().toString()+":"+controller.myUser.getPortTCP()+":"+controller.myUser.getPseudo()+":test"; + String toSend = controller.myUser.getAddIP().getHostAddress()+":"+controller.myUser.getPortTCP()+":"+controller.myUser.getPseudo()+":test"; DatagramPacket outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),itsIP, senderUDPport); try { @@ -86,7 +87,7 @@ public class ListeningThreadUDP extends ListeningThread{ else { try { // 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 - controller.myUser.addRemoteUser(InetAddress.getByName(tabMsg[0].split("/")[1]),Integer.parseInt(tabMsg[1]),tabMsg[2]); + controller.myUser.addRemoteUser(InetAddress.getByName(tabMsg[0]),Integer.parseInt(tabMsg[1]),tabMsg[2]); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); diff --git a/Application/Clavardage/src/model/User.java b/Application/Clavardage/src/model/User.java index 4e1c8fb..6a39a55 100644 --- a/Application/Clavardage/src/model/User.java +++ b/Application/Clavardage/src/model/User.java @@ -26,7 +26,7 @@ public abstract class User { this.pseudo = pseudo; this.addIP=addIP; this.portTCP=portTCP; - this.IPcode=addIP.hashCode(); + this.IPcode=hashCode(); } @@ -57,6 +57,15 @@ public abstract class User { } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + String ip=addIP.getHostAddress(); + result = prime * result + ((ip == null) ? 0 : ip.hashCode()); + result = prime * result + portTCP; + return result; + } @Override @@ -68,11 +77,29 @@ public abstract class User { if (getClass() != obj.getClass()) return false; User other = (User) obj; + if (addIP == null) { + if (other.addIP != null) + return false; + } else if (!addIP.equals(other.addIP)) + return false; if (portTCP != other.portTCP) return false; return true; } + + @Override + public String toString() { + return "User [pseudo=" + pseudo + ", addIP=" + addIP.getHostAddress() + ", portTCP=" + portTCP + ", IPcode=" + IPcode + "]"; + } + + + + + + + +