Passage en MVC

This commit is contained in:
Alexandre Gonzalvez 2020-12-09 12:18:50 +01:00
parent 85d0725ff3
commit 93e418dbee
12 changed files with 1170 additions and 0 deletions

View file

@ -0,0 +1,448 @@
package controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import model.LocalUser;
import view.Interface;
public class Controller {
/*** CONSTANTES ***/
final static int portUDPlistening_remoteUsr2 = 20002; // TO REMOVE when we use broadcast
final static int portUDPlistening_remoteUsr3 = 20003; // TO REMOVE when we use broadcast
/*** ATTRIBUTS ***/
private LocalUser myUser;
private Interface hisView;
private ListeningThreadUDP udp_connect_thread;
private ListeningThreadTCPConnection tcp_connect_thread;
private ArrayList<ListeningThreadTCPChat> tcp_chats_threads = new ArrayList<ListeningThreadTCPChat>(); // listes des utilisateurs actifs
/**
* 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 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
* @descrition
* <p>
* On récupère l'adresse de la machine, on demande un pseudo à l'utilisateur que l'on vérifie
* Une fois validé l'utilisateur devient actif :
* - écoute UDP pour les pseudos
* - écoute TCP pour de nouvelles conversation
* - notification aux autres utilisateurs actifs
* </p>
*/
private Controller(int portUDPsend,int portUDPlistening,int portTCP) {
InetAddress addIP = null;
try
{
addIP = InetAddress.getLocalHost();
}
catch(UnknownHostException e) {
JOptionPane.showMessageDialog(null ,"Could not find local address!");
}
this.myUser = new LocalUser("Unknown",addIP,portUDPsend,portUDPlistening,portTCP);
try {
this.myUser.setPseudo(this.initPseudo());
} catch (IOException e) {
e.printStackTrace();
}
this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this.myUser);
this.udp_connect_thread.start();
this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this.myUser);
this.tcp_connect_thread.start();
notify_remote_users();
}
/**
* 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 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
* @descrition
* <p>
* On récupère l'adresse de la machine, on demande un pseudo à l'utilisateur que l'on vérifie
* Une fois validé l'utilisateur devient actif :
* - écoute UDP pour les pseudos
* - écoute TCP pour de nouvelles conversation
* - notification aux autres utilisateurs actifs
* </p>
*/
private Controller(int portUDPsend,int portUDPlistening,int portTCP,String pseudo) {
InetAddress addIP = null;
try
{
addIP = InetAddress.getLocalHost();
}
catch(UnknownHostException e) {
JOptionPane.showMessageDialog(null ,"Could not find local address!");
}
this.myUser = new LocalUser(pseudo,addIP,portUDPsend,portUDPlistening,portTCP);
this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this.myUser);
this.udp_connect_thread.start();
this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this.myUser);
this.tcp_connect_thread.start();
notify_remote_users();
}
/*** GETTERS ***/
public LocalUser getMyUser() {
return myUser;
}
public Interface getHisView() {
return hisView;
}
public ListeningThreadUDP getUdp_connect_thread() {
return udp_connect_thread;
}
public ListeningThreadTCPConnection getTcp_connect_thread() {
return tcp_connect_thread;
}
public ArrayList<ListeningThreadTCPChat> getTcp_chats_threads() {
return tcp_chats_threads;
}
/*** SETTERS ***/
public void setMyUser(LocalUser myUser) {
this.myUser = myUser;
}
public void setHisView(Interface hisView) {
this.hisView = hisView;
}
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 setTcp_chats_threads(ArrayList<ListeningThreadTCPChat> tcp_chats_threads) {
this.tcp_chats_threads = tcp_chats_threads;
}
/**
* <p>
* Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux
* utilisateurs distants leurs informations
* </p>
*/
public String initPseudo() throws IOException {
String tmpPseudo = JOptionPane.showInputDialog(null, "Enter nickname:"); // Read user input
while(!(this.validatePseudo(tmpPseudo))) { // On demande aux autres utilisateurs de nous envoyer leurs informations et on test si le pseudo est déjà utilisé
tmpPseudo = JOptionPane.showInputDialog(null, "Enter another nickname:"); // Read user input
}
//sc1.close();
JOptionPane.showMessageDialog(null ,"Your nickname : " + tmpPseudo + " is valid !");
return tmpPseudo;
}
/**
* <p>
* Demande à l'utilisateur de rentrer un pseudo et valide de ce dernier en demandant aux
* utilisateurs distants leurs informations.
* On regarde si le pseudo est bien différent de l'ancien
* </p>
*/
private void changePseudo() throws IOException {
String oldPseudo = this.myUser.getPseudo(); //Saves the old one for comparison
String tmpPseudo = JOptionPane.showInputDialog(null, "Enter nickname:"); // Read user input
while(!(this.validatePseudo(tmpPseudo)) || tmpPseudo.equals(oldPseudo)) {
tmpPseudo = JOptionPane.showInputDialog(null, "Already exist, enter another nickname :"); // Read user input
}
this.myUser.setPseudo(tmpPseudo);
JOptionPane.showMessageDialog(null ,"Your new nickname : " + tmpPseudo + " is valid !");
this.notify_remote_users();
}
/**
* <p>
* *tmpPseudo : String => Le pseudo à valider
*</p><p>
* Envoi en broadcast (pour l'instant envoi sur les ports de notre ordinateur) d'une demande d'information
*</p><p>
* On attend les réponses pendant 5 secondes
*</p><p>
* On valide le pseudo en fonction des pseudos reçu
*</p><p>
* On en profite pour ajouter les utilisateurs répondant à notre liste d'utilisateur distant (RemoteUser)
* </p>
*/
public Boolean validatePseudo(String tmpPseudo) throws IOException {
// Call broadcast
InetAddress broadcastIP = InetAddress.getLocalHost(); // change to broadcast
//System.out.println(broadcastIP);
DatagramSocket dgramSocket = new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP());
byte[] buffer = new byte[256];
// Création du message à envoyer
String toSend = this.myUser.getAddIP()+":"+this.myUser.getPortUDPsend()+":test";
// Send to remote user 1
DatagramPacket outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, portUDPlistening_remoteUsr2);
dgramSocket.send(outPacket);
// Send to remote user 2
outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, portUDPlistening_remoteUsr3);
dgramSocket.send(outPacket);
// Initialisation des variables de la boucle
Boolean valid = true;
DatagramPacket inPacket;
String response = null;
String[] tabresponse= new String [4];
dgramSocket.setSoTimeout(1000);
Boolean arecu;
System.out.print("Wait for pseudo validation ...\n");
int nbReponse =0;
Date oldDate = new Date();
Date newDate = new Date();
while( (newDate.getTime()-oldDate.getTime()) < 5000 && valid) {
nbReponse++;
inPacket= new DatagramPacket(buffer, buffer.length);
arecu=true;
try{
dgramSocket.receive(inPacket);
}catch (Exception e) {
arecu=false;
}
buffer = inPacket.getData();
response = new String(buffer);
if(arecu) {
// On découpe la réponse en tableau de string ([adresseIP,tcpPort,nickname])
tabresponse = response.split(":");
// Affichage de la réponse
System.out.println("Remote user n°"+nbReponse+
"\nIP : "+tabresponse[0]+
"\nn°Port : "+tabresponse[1]+
"\npseudo : "+tabresponse[2]);
// 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]);
valid= (tmpPseudo.compareTo(tabresponse[2])!=0); // On regarde la différence entre notre pseudo et le pseudo reçu
}
newDate = new Date();
}
dgramSocket.close();
if(!valid) {
JOptionPane.showMessageDialog(null ,"Nickname : "+tmpPseudo +" is taken !");
}
return valid;
}
/**
* <p>
* En utilisant le port UDP d'envoi, on envoie en broadcast les informations nous concernant
* </p>
*/
public void notify_remote_users() {
// Création du socket d'envoi d'information
DatagramSocket dgramSocket= null;
try {
dgramSocket= new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP());
} catch (IOException e) {
e.printStackTrace();
}
// Construction du message à envoyer
String toSend = this.myUser.getAddIP().toString()+":"+this.myUser.getPortTCP()+":"+this.myUser.getPseudo()+":test";
DatagramPacket outPacket =null;
// Send information to usr2
if(this.myUser.getPortUDPlistening()!=portUDPlistening_remoteUsr2) {
outPacket = new DatagramPacket(toSend.getBytes(), toSend.length(),this.myUser.getAddIP(), portUDPlistening_remoteUsr2);
try {
dgramSocket.send(outPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
// Send information to usr3
if(this.myUser.getPortUDPlistening()!=portUDPlistening_remoteUsr3) {
outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),this.myUser.getAddIP(), portUDPlistening_remoteUsr3);
try {
dgramSocket.send(outPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
dgramSocket.close();
}
public void TCPmessage(int index) throws IOException {
Socket link=null;
String s1;
try {
link=new Socket(this.myUser.getRemoteUsersList().get(index).getAddIP(),this.myUser.getRemoteUsersList().get(index).getPortTCP());
System.out.println("Server is listening on port"+this.myUser.getPortTCP()+"of localhost");
}catch(IOException e) {
System.out.println("Server is not listening on port"+this.myUser.getPortTCP()+" of localhost");
}
BufferedReader in=null;
try {
in = new BufferedReader(new InputStreamReader(link.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
PrintWriter out = new PrintWriter(link.getOutputStream(),true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String input;
String s2 = (this.myUser.getPseudo()+" reçoit un message");
try {
while (!(input=in.readLine()).equals("end")) {
System.out.print("client_recoit:"+input);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*or (int i=0; i<4; i++) {
System.out.println("client envoie");
out.println("coucou \n");
}
out.println("end");*/
try {
link.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* <p>
* Laisse l'utilisateur choisir parmis la liste d'utilisateurs actifs celui avec lequel il souhaite échanger via un chat
*</p>
*/
public void getOneActiveUser() 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(userChatList.contains(this.myUser.getRemoteUsersList().get(index))) {
JOptionPane.showMessageDialog(null ,"User "+this.myUser.getRemoteUsersList().get(index).getPseudo()+" is already in chat with you");
}
else {
}
*/
// IF
// TODO regarder si ils sont déjà en conversation
// ELSE
// TODO Créer un nouveau thread tcp
int localUser_portTCP;
int remoteUser_portTCP;
//this.myUser.addChats(this.myUser.getRemoteUsersList().get(index), localUser_portTCP, remoteUser_portTCP);
JOptionPane.showMessageDialog(null ,"New chat with "+this.myUser.getRemoteUsersList().get(index).getPseudo());
}
else {
JOptionPane.showMessageDialog(null ,"Wrong index (no active at index number "+index+" )");
}
this.TCPmessage(index);
//sc2.close();
}
/********************************** 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());
}
}
/*************************************************************************************************************************/
public static void main(String[] args) throws IOException, InterruptedException {
Controller ctr2 = new Controller(12226,portUDPlistening_remoteUsr2,22222,"Mike");
Controller ctr3 = new Controller(12224,portUDPlistening_remoteUsr3,22223,"Alice");
Controller ctr1 = new Controller(12225,20001,22221); // Notre utilisateur local
// Fonction appelé par notre utilisateur local
ctr1.getOneActiveUser();
ctr1.changePseudo();
// On attends 5 secondes
System.out.println("Sleep mode for 5 seconds");
Thread.sleep(5000);
// On ferme les différents threads et socket d'écoute
ctr1.udp_connect_thread.close();
ctr2.udp_connect_thread.close();
ctr3.udp_connect_thread.close();
ctr1.tcp_connect_thread.close();
ctr2.tcp_connect_thread.close();
ctr3.tcp_connect_thread.close();
JOptionPane.showMessageDialog(null ,"End");
}
}

View file

@ -0,0 +1,17 @@
package controller;
import model.LocalUser;
public abstract class ListeningThread extends Thread{
protected LocalUser myUser;
public ListeningThread(String s,LocalUser myUser) {
super(s);
this.myUser = myUser;
}
public abstract void run();
public abstract void close();
}

View file

@ -0,0 +1,90 @@
package controller;
import model.LocalUser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ListeningThreadTCPChat extends ListeningThread{
private Socket socket;
/* CONSTRUCTOR OF ListeningThreadTCPConnection
* @parametres
* @param s : String => nom du thread
* @param myUser : User => utilisateur utilisant ce thread
* @description
* <p>
* </p>
*/
public ListeningThreadTCPChat(String s,LocalUser myUser,Socket socket) {
super(s,myUser);
this.socket=socket;
}
/* run
* @description
* <p>
*
* </p>
*/
public void run() {
Socket link = this.socket;
try {
BufferedReader in =new BufferedReader(new InputStreamReader(link.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out=null;
try {
out = new PrintWriter(link.getOutputStream(),true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(myUser.getPseudo()+" envoie un message");
out.println(dateFormat.format(date));
out.println("end");
String input;
/*while (!(input=in.readLine()).equals("end")) {
System.out.print("server_recoit:"+input);
}*/
try {
link.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* close
* @description
* <p>
* ferme le socket d'écoute TCP pour le chat
* interrupt TCP listening thread pour le chat
* </p>
*/
public void close() {
try {
this.socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("End of listing thread UDP ("+this.myUser.getPseudo()+")");
try {
this.interrupt();
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,91 @@
package controller;
import model.LocalUser;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ListeningThreadTCPConnection extends ListeningThread{
private Socket socket_tcp=null;
/* CONSTRUCTOR OF ListeningThreadTCPConnection
* @parametres
* @param s : String => nom du thread
* @param myUser : User => utilisateur utilisant ce thread
* @description
* <p>
* </p>
*/
public ListeningThreadTCPConnection(String s,LocalUser myUser) {
super(s,myUser);
}
public void accept(ServerSocket servSocket) throws IOException {
Socket socket_tcp= servSocket.accept();
ListeningThreadTCPChat threadtcpchat = new ListeningThreadTCPChat("Chat_with_"+myUser.getPseudo(),myUser,socket_tcp);
threadtcpchat.start();
threadtcpchat.interrupt();
}
/* run
* @description
* <p>
* écoutes les messages TCP tant que l'utilisateur est actif
* Traitement
* Si réception d'une demande, créer un thread pour la conversation
* </p>
*/
public void run(){
// Tant que l'utilisateur est actif on attends la demande de nouvelle conversation
while(true) {
ServerSocket servSocket=null;
try {
servSocket = new ServerSocket(myUser.getPortTCP());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
this.accept(servSocket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/* close
* @description
* <p>
* ferme le socket d'écoute TCO
* interrupt UDP listening threadS
* </p>
*/
public void close() {
try {
this.socket_tcp.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("End of listing thread TCP ("+this.myUser.getPseudo()+")");
try {
this.interrupt();
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,121 @@
package controller;
import model.LocalUser;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ListeningThreadUDP extends ListeningThread{
private DatagramSocket dgramSocket = null;
/* CONSTRUCTOR OF UserListeningThreadUDP
* @parametres
* @param s : String => nom du thread
* @param user : User => utilisateur utilisant ce thread
* @description
* <p>
* Appel du constructeur de la classe hérité
* Création d'un socket d'écoute UDP
* </p>
*/
public ListeningThreadUDP(String s,LocalUser myUser) {
super(s,myUser);
try {
this.dgramSocket = new DatagramSocket(this.myUser.getPortUDPlistening(),this.myUser.getAddIP());
} catch (IOException e) {
e.printStackTrace();
}
}
/* run
* @description
* <p>
* écoutes les messages UDP tant que l'utilisateur est actif
* Traitement
* 1) Si demande d'information => envoi ses informations
* 2) Si réception d'information => ajoute les informations
* </p>
*/
public void run(){
// Tant que l'utilisateur est actif on attends les messages des nouveaux utilisateurs et changements des utilisateurs actifs
while(true) {
// Réception du message
byte[] buffer = new byte[256];
DatagramPacket inPacket= new DatagramPacket(buffer, buffer.length);
try {
dgramSocket.receive(inPacket);
} catch (Exception e) {
e.printStackTrace();
}
buffer = inPacket.getData();
// Traitement en fonction du message reçu
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
} 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 = myUser.getAddIP().toString()+":"+myUser.getPortTCP()+":"+myUser.getPseudo()+":test";
DatagramPacket outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),itsIP, senderUDPport);
try {
dgramSocket.send(outPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
// Si un nouvel utilisateur passe en mode actif ou changement d'information
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
this.myUser.addRemoteUser(InetAddress.getByName(tabMsg[0].split("/")[1]),Integer.parseInt(tabMsg[1]),tabMsg[2]);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/* close
* @description
* <p>
* Ferme le socket d'écoute UDP
* Interrompt le thread d'écoute UDP
* </p>
*/
public void close() {
this.dgramSocket.close();
System.out.println("End of listing thread UDP ("+this.myUser.getPseudo()+")");
try {
this.interrupt();
}catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,50 @@
package model;
import java.util.ArrayList;
public class Chat {
/*** ATTRIBUTS ***/
private int localUser_portTCP;
private int remoteUser_portTCP;
private ArrayList<RemoteUser> remoteUsersChatList = new ArrayList<RemoteUser>(); // listes des utilisateurs sur ce chat
/**
* Constructor of Chat (local)
* @parametres
* @param remoteUser : remoteUser => référence de l'utilisateur distant
* @param localUser_portTCP : int => le numéro de port TCP d'écoute de la conversation de l'utilisateur local
* @param remoteUser_portTCP : int => le numéro de port TCP d'écoute de la conversation de l'utilisateur distant
* @description
* <p>
*
* </p>
*/
public Chat(RemoteUser rm,int localUser_portTCP,int remoteUser_portTCP) {
this.localUser_portTCP = localUser_portTCP;
this.remoteUser_portTCP = remoteUser_portTCP;
remoteUsersChatList.add(rm);
}
/*** GETTERS ***/
public int getLocalUser_portTCP() {
return localUser_portTCP;
}
public int getRemoteUser_portTCP() {
return remoteUser_portTCP;
}
public ArrayList<RemoteUser> getRemoteUsersChatList() {
return remoteUsersChatList;
}
/*** SETTERS ***/
public void setLocalUser_portTCP(int localUser_portTCP) {
this.localUser_portTCP = localUser_portTCP;
}
public void setRemoteUser_portTCP(int remoteUser_portTCP) {
this.remoteUser_portTCP = remoteUser_portTCP;
}
public void setRemoteUsersChatList(ArrayList<RemoteUser> remoteUsersChatList) {
this.remoteUsersChatList = remoteUsersChatList;
}
}

View file

@ -0,0 +1,95 @@
package model;
import java.net.InetAddress;
import java.util.ArrayList;
public class LocalUser extends User{
/*** ATTRIBUTS ***/
private int portUDPsend;
private int portUDPlistening;
private ArrayList<RemoteUser> remoteUsersList = new ArrayList<RemoteUser>(); // listes des utilisateurs actifs
private ArrayList<Chat> chats = new ArrayList<Chat>();
/**
* Constructor of LocalUser
* @parametres
* @param pseudo : String
* @param addIP : InetAddress
* @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 portTCP : int => le numéro de port pour commencer une nouvelle conversation
* @description
* <p>
*
* </p>
*/
public LocalUser(String pseudo,InetAddress addIP,int portUDPsend,int portUDPlistening,int portTCP){
super(pseudo,addIP,portTCP);
this.portUDPsend = portUDPsend;
this.portUDPlistening = portUDPlistening;
}
/*** GETTERS ***/
public int getPortUDPsend() {
return portUDPsend;
}
public int getPortUDPlistening() {
return portUDPlistening;
}
public ArrayList<RemoteUser> getRemoteUsersList() {
return remoteUsersList;
}
public ArrayList<Chat> getChats() {
return chats;
}
/*** SETTERS ***/
public void setPortUDPsend(int portUDPsend) {
this.portUDPsend = portUDPsend;
}
public void setPortUDPlistening(int portUDPlistening) {
this.portUDPlistening = portUDPlistening;
}
/**
* @parameters
* @param remoteUserIP : InetAddress => l'adresse IP de l'utilisateur distant
* @param remoteUserPortTCP : int => le numéro de port TCP d'écoute de l'utilisateur distant
* @param remoteUserPseudo : String => le pseudo de l'utilisateur distant
* <p>
* Ajout ou mise à jour l'utilisateur distant dans notre liste d'utilisateur distant
* </p>
*/
public void addRemoteUser(InetAddress remoteUserIP, int remoteUserPortTCP,String remoteUserPseudo) {
RemoteUser tmpRemoteUser = new RemoteUser(remoteUserPseudo,remoteUserIP,remoteUserPortTCP);
int index = this.remoteUsersList.indexOf(tmpRemoteUser);
if(index!=-1) {
System.out.println("("+this.pseudo+") - "+"MAJ, IP(port) of user : "+remoteUserPseudo+" => "+remoteUserIP+"("+remoteUserPortTCP+")");
this.remoteUsersList.set(index,tmpRemoteUser);
}
else {
System.out.println("("+this.pseudo+") - "+"Add new user IP(port) of user : "+remoteUserPseudo+" => "+remoteUserIP+"("+remoteUserPortTCP+")");
this.remoteUsersList.add(tmpRemoteUser);
}
}
/**
* @parameters
* @param remoteUser : remoteUser => référence de l'utilisateur distant
* @param localUser_portTCP : int => le numéro de port TCP d'écoute de la conversation de l'utilisateur local
* @param remoteUser_portTCP : int => le numéro de port TCP d'écoute de la conversation de l'utilisateur distant
* <p>
* Ajout ou mise à jour l'utilisateur distant dans notre liste d'utilisateur distant
* </p>
*/
public void addChats(RemoteUser rm,int localUser_portTCP,int remoteUser_portTCP) {
Chat newChat= new Chat(rm,localUser_portTCP,remoteUser_portTCP);
this.chats.add(newChat);
}
}

View file

@ -0,0 +1,46 @@
package model;
import java.net.InetAddress;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public abstract class Message {
/*** ATTRIBUTS ***/
private Date date;
private InetAddress autorIP;
/**
* Constructor of Message
* @parametres
* @param authorIP : InetAddress
* @description
* <p>
*
* </p>
*/
public Message(InetAddress autorIP) {
this.autorIP = autorIP;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
this.date = new Date();
}
/*** GETTERS ***/
public Date getDate() {
return date;
}
public InetAddress getAutorIP() {
return autorIP;
}
/*** SETTERS ***/
public void setDate(Date date) {
this.date = date;
}
public void setAutorIP(InetAddress autorIP) {
this.autorIP = autorIP;
}
public abstract Object getMessage();
}

View file

@ -0,0 +1,22 @@
package model;
import java.net.InetAddress;
public class Msg_Text extends Message{
/*** ATTRIBUT ***/
private String text;
public Msg_Text(InetAddress autorIP,String text) {
super(autorIP);
this.text = text;
}
@Override
public String getMessage() {
return this.text;
}
}

View file

@ -0,0 +1,11 @@
package model;
import java.net.InetAddress;
public class RemoteUser extends User{
public RemoteUser(String pseudo, InetAddress addIP, int portTCP) {
super(pseudo, addIP, portTCP);
}
}

View file

@ -0,0 +1,52 @@
package model;
import java.net.*;
public abstract class User {
/*** ATTRIBUTS ***/
protected String pseudo;
protected InetAddress addIP;
protected int portTCP;
/**
* Constructor of User (local)
* @parametres
* @param pseudo : String
* @param addIP : InetAddress
* @param portTCP : int => le numéro de port pour commencer une nouvelle conversation
* @description
* <p>
*
* </p>
*/
public User(String pseudo,InetAddress addIP,int portTCP){
this.pseudo = pseudo;
this.addIP=addIP;
this.portTCP=portTCP;
}
/*** GETTERS ***/
public String getPseudo() {
return pseudo;
}
public InetAddress getAddIP() {
return addIP;
}
public int getPortTCP() {
return portTCP;
}
/*** SETTERS ***/
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public void setAddIP(InetAddress addIP) {
this.addIP = addIP;
}
public void setPortTCP(int portTCP) {
this.portTCP = portTCP;
}
}

View file

@ -0,0 +1,127 @@
package view;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Interface implements ActionListener {
private String Pseudolabeltext = "";
final JLabel Pseudolabel = new JLabel("Pseudo: " + Pseudolabeltext);
private JTextField PseudotextField;
private JButton convertPseudo;
//Specifies the look and feel to use. Valid values:
//null (use the default), "Metal", "System", "Motif", "GTK+"
final static String LOOKANDFEEL = null;
public Component createComponents() {
PseudotextField = new JTextField();
PseudotextField.setColumns(10);
PseudotextField.setText("Enter pseudo");
convertPseudo = new JButton("Convert Pseudo");
convertPseudo.addActionListener(this);
Pseudolabel.setLabelFor(PseudotextField);
/*
* An easy way to put space between a top-level container
* and its contents is to put the contents in a JPanel
* that has an "empty" border.
*/
JPanel pane = new JPanel(new GridLayout(0, 1));
pane.add(PseudotextField);
pane.add(Pseudolabel);
pane.add(convertPseudo);
pane.setBorder(BorderFactory.createEmptyBorder(
30, //top
30, //left
10, //bottom
30) //right
);
return pane;
}
// Modify the event handler code depending on which button is pressed.
// If the 1st button is pressed, increase the numClicks value by 1, else
// increase the value by 1000.
public void actionPerformed(ActionEvent e) {
String texteUtilisateur = PseudotextField.getText();
Pseudolabel.setText("Pseudo: " + texteUtilisateur);
}
private static void initLookAndFeel() {
// Swing allows you to specify which look and feel your program uses-
// -Java,
// GTK+, Windows, and so on as shown below.
String lookAndFeel = null;
if (LOOKANDFEEL != null) {
if (LOOKANDFEEL.equals("Metal")) {
lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
} else if (LOOKANDFEEL.equals("System")) {
lookAndFeel = UIManager.getSystemLookAndFeelClassName();
} else if (LOOKANDFEEL.equals("Motif")) {
lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
} else if (LOOKANDFEEL.equals("GTK+")) { //new in 1.4.2
lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
} else {
System.err.println("Unexpected value of LOOKANDFEEL specified: " + LOOKANDFEEL);
lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
}
try {UIManager.setLookAndFeel(lookAndFeel);
} catch (ClassNotFoundException e) {
System.err.println("Couldn't find class for specified look and feel:" + lookAndFeel);
System.err.println("Did you include the L&F library in the class path?");
System.err.println("Using the default look and feel.");
} catch (UnsupportedLookAndFeelException e) {
System.err.println("Can't use the specified look and feel (" + lookAndFeel+ ") on this platform.");
System.err.println("Using the default look and feel.");
} catch (Exception e) {
System.err.println("Couldn't get specified look and feel (" + lookAndFeel + "), for some reason.");
System.err.println("Using the default look and feel.");
e.printStackTrace();
}
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Set the look and feel.
initLookAndFeel();
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("SwingApplication");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Interface app = new Interface();
Component contents = app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
/*
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this applications GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}*/
}