Echange de messages ok entre deux PCs

This commit is contained in:
Morgane Foussats 2021-01-05 19:15:25 +01:00
incheckning ed4f39a6a0
61 ändrade filer med 1806 tillägg och 0 borttagningar

15
chat/.classpath Normal file
Visa fil

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="lib/mysql-connector-java-5.0.5-bin.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin"/>
</classpath>

17
chat/.project Normal file
Visa fil

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>chat</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

Visa fil

@ -0,0 +1,15 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=13
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=13
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=13

Binär
chat/bin/controller/Agent.class Normal file

Binary file not shown.

Binary file not shown.

Binär
chat/bin/controller/Test.class Normal file

Binary file not shown.

Binary file not shown.

Binär
chat/bin/gui/FenetreAcc$1.class Normal file

Binary file not shown.

Binär
chat/bin/gui/FenetreAcc.class Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binär
chat/bin/gui/FenetreChat.class Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binär
chat/bin/gui/FenetreMenu.class Normal file

Binary file not shown.

Binär
chat/bin/gui/package-info.class Normal file

Binary file not shown.

Binär
chat/bin/gui/panda.png Normal file

Binary file not shown.

Efter

Bredd:  |  Höjd:  |  Storlek: 5,8 KiB

Binär
chat/bin/images/panda.png Normal file

Binary file not shown.

Efter

Bredd:  |  Höjd:  |  Storlek: 5,8 KiB

Binär
chat/bin/model/Contact.class Normal file

Binary file not shown.

Binary file not shown.

Binär
chat/bin/model/Message.class Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binär
chat/bin/module-info.class Normal file

Binary file not shown.

Binär
chat/bin/network/Manager.class Normal file

Binary file not shown.

Binär
chat/bin/network/TCPChat.class Normal file

Binary file not shown.

Binary file not shown.

Binär
chat/bin/network/Tools.class Normal file

Binary file not shown.

Binär
chat/bin/network/UDPInput.class Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Visa fil

@ -0,0 +1,293 @@
package controller;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import gui.FenetreChat;
import model.*;
import network.*;
public class Agent implements PropertyChangeListener{
private Contact user;
private UDPInput BIn;
private UDPOutput BOut;
//private TCPChat TCPSend;
private TCPServer server;
private ListeContacts list;
private InetAddress localAddress;
private InetAddress broadcast;
private ArrayList<TCPChat> listTCP;
private DataBase db;
private PropertyChangeSupport support;
public Agent(InetAddress address, int portIn, int portOut) throws IOException {
this.user = new Contact("", address, portIn);
this.BIn = new UDPInput(user.getAddress(), portIn);
this.BOut = new UDPOutput(user, portOut);
this.server = new TCPServer(user.getPort(), user.getAddress());
this.server.addPropertyChangeListener(this);
//this.TCPSend = new TCPChat(user);
this.list = ListeContacts.getInstance();
this.localAddress=Tools.getAdress()[0];
this.broadcast= Tools.getAdress()[1];
this.db = DataBase.getInstance();
this.listTCP = new ArrayList<TCPChat>();
this.support = new PropertyChangeSupport(this);
this.BIn.addPropertyChangeListener(this);
BIn.start();
}
public void propertyChange(PropertyChangeEvent evt) {
switch (evt.getPropertyName()) {
case "Msg UDP Recu" :
System.out.println("envoi message");
Message msg = BIn.getMessage();
try {
handleMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
break;
case "session chat demarree" :
System.out.println("dans session demarree");
TCPChat tcpChat = this.server.getConnexionTCPChat();
tcpChat.addPropertyChangeListener(this);
this.listTCP.add(tcpChat);
break;
case "Msg TCP Recu" :
SimpleAttributeSet left = new SimpleAttributeSet();
StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);
StyleConstants.setForeground(left, Color.RED);
System.out.println("dans property change");
TCPChat tcpChatCo = this.listTCP.get(0);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
MessageChat msgRecu = tcpChatCo.getMessageRecu();
//FenetreChat.getTa().append("kevin"+ " : "+msgRecu.getMessage()+"\n");
StyledDocument doc = FenetreChat.getDoc();
try {
doc.insertString(doc.getLength(), "\n"+msgRecu.getMessage(), left );
} catch (BadLocationException e) {
e.printStackTrace();
}
doc.setParagraphAttributes(doc.getLength(), 1, left, false);
break;
}
}
//Envoi sur 5001 et reçoit sur 5000
public void testSendBroadcast() throws IOException, InterruptedException {
MessagePseudo msg = new MessagePseudo(this.user.getAddress(), Tools.getLocalIp(), user.getPort(), 14000, 1, "Michel");
BOut.send(msg, user.getAddress(), user.getPort());
Thread.sleep(10);
MessagePseudo msgRecu = BIn.getMessage();
handleMessage(msgRecu);
MessagePseudo msg2 = new MessagePseudo(this.user.getAddress(), Tools.getLocalIp(), user.getPort(), 14000, 1, "Jacques");
BOut.send(msg2, user.getAddress(), user.getPort());
Thread.sleep(10);
MessagePseudo msgRecu2 = BIn.getMessage();
handleMessage(msgRecu2);
MessagePseudo msg3 = new MessagePseudo(this.user.getAddress(), Tools.getLocalIp(), user.getPort(), 14000, 1, "Bob");
BOut.send(msg3, user.getAddress(), user.getPort());
Thread.sleep(10);
MessagePseudo msgRecu3 = BIn.getMessage();
handleMessage(msgRecu3);
choisirPseudo("Bob");
choisirPseudo("Patrick");
}
/*public void testSendTCP() throws IOException, InterruptedException {
TCPSend.sendMsg("COUCOU");
Thread.sleep(1000);
TCPSend.sendMsg("Ca va ?");
Thread.sleep(1000);
TCPSend.sendMsg("Non je suis KO");
Thread.sleep(1000);
TCPSend.sendMsg("Moi aussi :'(");
Thread.sleep(1000);
}*/
/*type 0 : premier message de broadcast
* type, 1 : deuxieme message de broadcast avec pseudo
* type 2 : Message de déconnexion
*/
public void handleMessage(Message msg) throws IOException {
switch(msg.getTypeMessage()) {
case 0 :
System.out.println("Envoi message présentation");
MessagePseudo msgPresentation = new MessagePseudo(this.localAddress, msg.getAddressSrc(), this.user.getPort(), msg.getPortSrc(), 1, this.user.getPseudo());
BOut.send(msgPresentation, msg.getAddressSrc(), msg.getPortSrc());
break;
case 1 :
MessagePseudo msgPseudo = (MessagePseudo) msg;
if(!list.pseudoExist(msgPseudo.getPseudo())) {
Contact newUser = new Contact(msgPseudo.getPseudo(), msgPseudo.getAddressSrc(), msgPseudo.getPortSrc());
list.addContact(newUser);
}
break;
/*case 2 :
MessageDeconnexion messageDeconnexion = (MessageDeconnexion) msg;
if(list.pseudoExist(messageDeconnexion.getPseudo())){
Contact contact = list.findContact(messageDeconnexion.getPseudo());
list.deleteContact(contact);
}*/
}
}
public boolean connect(String pseudo) throws IOException, InterruptedException {
MessagePseudo msg_connexion = new MessagePseudo(this.localAddress, this.broadcast, this.user.getPort(), 25000, 0, "");
BOut.send(msg_connexion, this.broadcast, 25000);
Thread.sleep(5000);
ArrayList<MessagePseudo> msg_recus = BIn.getListMessage();
for(int i =0; i<msg_recus.size(); i++) {
handleMessage(msg_recus.get(i));
}
boolean pseudoOK = choisirPseudo(pseudo);
list.addContact(user);
if(pseudoOK){
int id = db.addUser(pseudo);
this.user.setId(id);
MessagePseudo msgPresentation = new MessagePseudo(this.localAddress, this.broadcast, this.user.getPort(), 25000, 1, this.user.getPseudo());
BOut.send(msgPresentation, this.broadcast, 25000);
this.user.setStatut("En ligne");
System.out.println("Connexion réussie avec le pseudo : "+pseudo);
}else {
System.out.println("Echec de la connexion, veuillez choisir un autre pseudo");
}
return pseudoOK;
}
public boolean choisirPseudo(String pseudo) {
if(!list.pseudoExist(pseudo)){
user.setPseudo(pseudo);
System.out.println("Pseudo set : "+pseudo);
return true;
}else {
System.out.println("Pseudo déjà utilisé");
return false;
}
}
public void deconnexion() throws IOException {
MessageDeconnexion msgDeconnexion = new MessageDeconnexion(this.localAddress, this.broadcast, this.user.getPort(), 25000, 3, user.getPseudo());
BOut.send(msgDeconnexion, this.broadcast, this.user.getPort());
System.exit(1);
}
public boolean changerPseudo(String pseudo) {
boolean changeOK = choisirPseudo(pseudo);
if(changeOK){
System.out.println("Pseudo changé à : "+pseudo);
db.updatePseudo(this.user.getId(), pseudo);
return true;
}else {
System.out.println("Veuillez choisir un autre pseudo");
return false;
}
}
public boolean chatExists(int destID) {
boolean chatExists = false;
for(TCPChat tcp : listTCP) {
if(tcp.getDestID()==destID) {
chatExists = true;
}
}
return chatExists;
}
public void createChat (int destId, String destPseudo) throws IOException {
boolean chatExists = chatExists(destId);
if(!chatExists) {
for(Contact user : list.getListe()) {
if(user.getPseudo().equals(destPseudo)) {
TCPChat connexionTCP = new TCPChat(user, destId);
listTCP.add(connexionTCP);
connexionTCP.addPropertyChangeListener(this);
}
}
}
}
public void addPropertyChangeListener(PropertyChangeListener pcl, String propertyName){
this.support.addPropertyChangeListener(propertyName, pcl);
}
public void deletePropertyChangeListener(PropertyChangeListener pcl, String propertyName){
this.support.removePropertyChangeListener(propertyName,pcl);
}
public Contact getUser() {
return user;
}
public void setUser(Contact user) {
this.user = user;
}
public ListeContacts getList() {
return list;
}
public void setList(ListeContacts list) {
this.list = list;
}
public DataBase getDb() {
return db;
}
public void setDb(DataBase db) {
this.db = db;
}
public ArrayList<TCPChat> getListeTCPChat(){
return listTCP;
}
public TCPChat getTCPChat() {
return this.listTCP.remove(0);
}
}

Visa fil

@ -0,0 +1,200 @@
package controller;
import java.sql.*;
public class DataBase {
//Connexion serveur GEI
//login : tp_servlet_018
//password : Taey2Aje
//Plus d'infs connexion sur moodle
private static DataBase instance = null;
public Connection connexion;
private DataBase() {
try {
Class.forName("com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
try {
connexion = DriverManager.getConnection("jdbc:mysql://srv-bdens.insa-toulouse.fr:3306/tp_servlet_018?useSSL=false", "tp_servlet_018", "Taey2Aje");
//connexion = DriverManager.getConnection("jdbc:mysql://localhost/test?characterEncoding=utf8", "root","root");
}catch(SQLException e) {
e.printStackTrace();
}
}
public static DataBase getInstance() {
synchronized (DataBase.class) {
DataBase db = instance;
if(db == null) {
db = new DataBase();
}
return db;
}
}
//retourne l'id associé au user ajouté
public int addUser(String pseudo) {
String query = "INSERT INTO users (pseudo, statut) VALUES (?, ?)";
PreparedStatement pStat = null;
try {
pStat = connexion.prepareStatement(query);
pStat.setString(1, pseudo);
pStat.setString(2, "En ligne");
pStat.executeUpdate();
}catch (SQLException e) {
e.printStackTrace();
}
query = "SELECT * FROM users WHERE pseudo=?";
int id =0;
try {
pStat = connexion.prepareStatement(query);
pStat.setString(1, pseudo);
ResultSet resId = pStat.executeQuery();
if(resId.first()) {
id = resId.getInt("id");
}
}catch(SQLException e) {
e.printStackTrace();
}
return id;
}
public String getPseudoFromId(int id) {
String pseudo = null;
String query = "SELECT * FROM users WHERE id=?";
PreparedStatement pStat = null;
try {
pStat = connexion.prepareStatement(query);
pStat.setInt(1, id);
ResultSet resPseudo = pStat.executeQuery();
if(resPseudo.first()) {
pseudo = resPseudo.getString("pseudo");
}
}catch(SQLException e) {
e.printStackTrace();
}
return pseudo;
}
public int getIdFromPseudo(String pseudo) {
int id = -1;
String query = "SELECT * FROM users WHERE pseudo='" + pseudo + "'";
PreparedStatement pStat = null;
try {
pStat = connexion.prepareStatement(query);
//pStat.setString(1, pseudo);
ResultSet resId = pStat.executeQuery();
if(resId.next()) {
id = resId.getInt(1);
}
}catch(SQLException e) {
e.printStackTrace();
}
return id;
}
public void deleteFromId(int id) {
String query = "DELETE FROM `users` WHERE `id` = ?";
PreparedStatement pStat = null;
try {
pStat = connexion.prepareStatement(query);
pStat.setInt(1, id);
pStat.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}
}
public void updatePseudo(int id, String pseudo) {
String query = "UPDATE `users` SET `pseudo`=? WHERE id=?";
PreparedStatement pStat = null;
try {
pStat = connexion.prepareStatement(query);
pStat.setString(1, pseudo);
pStat.setInt(2, id);
pStat.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}
}
//chat table : nom : id1id2
//colonnes :
//id (l'id unique du message)
//id1 et id2 les id des deux users qui se parlent
//message : le message envoyé
//date : la date d'envoi du msg
public void newChatTable (int id1, int id2) {
int idSrc = id1;
int idDest = id2;
if(id1>id2) {
idSrc = id2;
idDest = id1;
}
String nameTable = idSrc+"_"+idDest;
String query = "CREATE TABLE " +nameTable+" (\n" +
"id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, \n" +
"idSrc INT NOT NULL,\n" +
"idDest INT NOT NULL,\n" +
"message MEDIUMTEXT NOT NULL,\n" +
"date DATE NOT NULL\n" +
");";
PreparedStatement pStat = null;
try {
pStat = connexion.prepareStatement(query);
pStat.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}
}
public boolean tableChatExists(int id1, int id2) {
int idSrc = id1;
int idDest = id2;
boolean res = true;
if(id1>id2) {
idSrc = id2;
idDest = id1;
}
String nameTable = idSrc+"_"+idDest;
String query = "SELECT * FROM " + nameTable;
PreparedStatement pStat = null;
try {
pStat = connexion.prepareStatement(query);
pStat.executeQuery();
}catch(SQLException e) {
res = false;
//e.printStackTrace();
}
return res;
}
//il faut mettre dans l'ordre idSrc pour id1 et id Dest pour id2 dans les params
public void addMessage(int id1, int id2, String message) {
int idSrc = id1;
int idDest = id2;
if(id1>id2) {
idSrc = id2;
idDest = id1;
}
String nameTable = idSrc+"_"+idDest;
String query = "INSERT INTO " + nameTable + "(idSrc, idDest, message, date) VALUES (?, ?, ?, CURRENT_TIME)";
PreparedStatement pStat = null;
try {
pStat = connexion.prepareStatement(query);
pStat.setInt(1, id1);
pStat.setInt(2, id2);
pStat.setString(3, message);
pStat.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}
}
}

Visa fil

@ -0,0 +1,15 @@
package controller;
import java.io.IOException;
import network.Tools;
public class Test {
public static void main(String args[]) throws IOException, InterruptedException {
Agent agent1 = new Agent(Tools.getAdress()[0], 22001, 22000);
int id = agent1.getDb().getIdFromPseudo(agent1.getUser().getPseudo());
System.out.println("ID : "+id);
//Tools.printInterfaces();
}
}

Visa fil

@ -0,0 +1 @@
package controller;

Visa fil

@ -0,0 +1,125 @@
package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JOptionPane;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.IOException;
import controller.*;
import network.Tools;
public class FenetreAcc implements ActionListener {
JFrame frame;
JPanel panel;
JTextField pseudofield;
JLabel Text;
JButton Connexion;
/*
* Constructeur d'une fenetre d'affichage pour la connexion d'un utilisateur.
* Cette fenetre sera munie d'un bouton de connexion et d'une zone de saisie de pseudo.
*/
public FenetreAcc() {
// TODO Auto-generated constructor stub
//creer une instance JFrame
frame = new JFrame("Fenetre accueil");
//sortir quand lutilisateur ferme le frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// fixer les dimensions de la fenetre
frame.setSize(new Dimension(120, 40));
//Creer le JPanel
panel = new JPanel(new GridLayout(3,1));
//Ajouter les elements
this.addWidgets();
//Set the default button.
frame.getRootPane().setDefaultButton(Connexion);
//Ajouter le panel a la window
frame.getContentPane().add(panel, BorderLayout.CENTER);
//L'utilisateur ne pourra pas aggrandir la fenetre
this.frame.setResizable(false);
//Afficher la fenetre
frame.pack();
frame.setVisible(true);
}
private void addWidgets() {
// Créer Zone d'insertion de texte pour le pseudo
this.pseudofield = new JTextField(2);
// creation d'un label qui contiendra un txt au centre
this.Text = new JLabel("Type your user name", SwingConstants.CENTER);
//Ajout d'un bouton Connexion
this.Connexion = new JButton("Connexion");
//On associe au bouton Connexion des actions a realiser
this.Connexion.addActionListener(this);
// On ajouter les differents elements au panel
panel.add(pseudofield);
panel.add(Text);
panel.add(Connexion);
//ajouter un effet de bord transparent au composant Jlabel
Text.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
}
public void actionPerformed(ActionEvent event) {
// on recupere le texte entree dans la zone de saisie
String pseudo = pseudofield.getText();
// On crée un objet de type ChatApp
Agent agent;
boolean connexion;
try {
agent = new Agent(Tools.getAdress()[0], 25001, 25000);
// on tente une connexion avec ce pseudo
connexion = agent.connect(pseudo);
// Dans les deux cas de figures (reussite ou echec) on affiche un pop-up pour expliquer la situation
if(connexion) {
// La connexion a reussi
JOptionPane.showMessageDialog(frame, "Bonjour " + pseudo) ;
frame.dispose();
// on lance une nouvelle fenetre de type View_Menu
FenetreMenu fenetreCourante= new FenetreMenu(agent);
}
else {
// La connexion a echoue, il est possible de rentrer un nouveau pseudo
JOptionPane.showMessageDialog(frame, "Echec de Connexion , ce pseudo est deja pris !");
}
} catch (IOException e) {
System.out.println("Création thread impossible");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("connect impossible");
e.printStackTrace();
}
}
private static void createAndShowGUI() {
// Etre certain d'avoir une joli fenetre
JFrame.setDefaultLookAndFeelDecorated(true);
// On crée une fentre d'acceuil
FenetreAcc fenetre = new FenetreAcc();
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Visa fil

@ -0,0 +1,193 @@
package gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.List;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import controller.Agent;
import model.Contact;
import model.MessageChat;
import network.TCPChat;
import java.awt.*;
public class FenetreChat extends JFrame {
JFrame frame;
Agent agent;
Contact dest; //destinataire du message
Contact user; //utilisateur
WindowAdapter wa;
JPanel panel;
static JTextArea ta;
static StyledDocument doc;
public FenetreChat(Agent agent, String userString) {
this.frame = new JFrame("Fenetre Chat avec "+ userString);
this.agent = agent;
this.user = agent.getUser();
this.dest = agent.getList().findContact(userString);
this.frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.frame.setSize(new Dimension(400, 400));
this.frame.setResizable(true);
this.wa = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int quitter = FenetreMenu.fenetreFermeture();
if(quitter == 0) {
frame.dispose();
}
}};
addWidgets();
frame.addWindowListener(wa);
frame.setVisible(true);
}
private void addWidgets() {
JTextPane textPane = new JTextPane();
this.doc = textPane.getStyledDocument();
SimpleAttributeSet right = new SimpleAttributeSet();
StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
StyleConstants.setForeground(right, Color.BLUE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{394, 0};
gridBagLayout.rowHeights = new int[]{16, 220, 74, 0};
gridBagLayout.columnWeights = new double[]{0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
this.frame.getContentPane().setLayout(gridBagLayout);
this.panel = new JPanel();
//zone pour rentrer les message à envoyer
JTextArea text = new JTextArea(10, 3);
text.setForeground(Color.BLACK);
text.setFont(new Font("Century Schoolbook", Font.PLAIN, 11));
text.setText("Enter your message");
text.setLineWrap(true);
JScrollPane sp = new JScrollPane(text);
//zone affichage texte
//this.ta = new JTextArea(20, 20);
//this.ta.setLineWrap(true);
//this.ta.setText("");
JScrollPane sp2 = new JScrollPane(textPane);
//this.ta.setEditable(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(0, 0, 5, 0);
gbc.gridx = 0;
gbc.gridy = 1;
frame.getContentPane().add(sp2, gbc);
//bouton envoyer
JButton envoyer = new JButton("Send");
frame.getRootPane().setDefaultButton(envoyer);
envoyer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String message = text.getText();
System.out.println("Message :"+ message);
System.out.println(dest);
int idUser = agent.getDb().getIdFromPseudo(user.getPseudo());
System.out.println("IDuser = "+idUser);
int idDest = agent.getDb().getIdFromPseudo(dest.getPseudo());
System.out.println("IDdest = "+idDest);
try {
TCPChat tcpChat = null;
for(TCPChat tcp : agent.getListeTCPChat()) {
if (tcp.getDestID() == idDest) {
tcpChat = tcp;
}
}
//text.append(message);
text.setText("");
//ta.append(agent.getUser().getPseudo()+ " : "+message+"\n");
//ta.setText("");
tcpChat.sendMsg(message);
doc.insertString(doc.getLength(), "\n"+message, right );
doc.setParagraphAttributes(doc.getLength(), 1, right, false);
if(agent.getDb().tableChatExists(idUser, idDest)) {
agent.getDb().addMessage(idUser, idDest, message);
}else {
agent.getDb().newChatTable(idUser, idDest);
agent.getDb().addMessage(idUser, idDest, message);
}
} catch (IOException | BadLocationException e1) {
System.out.println("Envoi du message impossible");
e1.printStackTrace();
}
}});
panel.add(BorderLayout.CENTER, sp);
panel.add(BorderLayout.SOUTH,envoyer);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.anchor = GridBagConstraints.NORTH;
gbc_panel.fill = GridBagConstraints.HORIZONTAL;
gbc_panel.gridx = 0;
gbc_panel.gridy = 2;
frame.getContentPane().add(panel, gbc_panel);
}
public static JTextArea getTa() {
return ta;
}
public void setTa(JTextArea ta) {
this.ta = ta;
}
public static StyledDocument getDoc() {
return doc;
}
public static void setDoc(StyledDocument doc) {
FenetreChat.doc = doc;
}
/*@Override
public void propertyChange(PropertyChangeEvent evt) {
switch (evt.getPropertyName()) {
case "Msg TCP Recu" :
System.out.println("dans property change");
TCPChat tcpChat = agent.getTCPChat();
MessageChat msgRecu = tcpChat.getMessageRecu();
ta.append(dest.getPseudo()+ " : "+msgRecu.getMessage()+"\n");
break;
}
}*/
}

Visa fil

@ -0,0 +1,234 @@
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import controller.Agent;
import model.Contact;
public class FenetreMenu {
JFrame frame;
JPanel panel;
JMenuBar menu;
Agent agent;
JLabel jlabel;
JLabel texte;
JLabel liste;
WindowAdapter wa ;
public FenetreMenu(Agent agent) {
this.agent = agent;
frame = new JFrame("Fenêtre menu");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(new Dimension(100, 100));
wa = new WindowAdapter(){
public void windowClosing(WindowEvent e){
int reponse = fenetreFermeture();
if (reponse==0){
try {
// on deconnecte l'app avant de quitter
// Tout les utilisateurs sont donc prevenus du depart
agent.deconnexion();
} catch (IOException e1) {
e1.printStackTrace();
}
frame.dispose();
}
}};
frame.addWindowListener(wa);
menu = new JMenuBar();
//Creation d'un JPanel
panel = new JPanel(new GridLayout(3,1));
panel.setForeground(SystemColor.menuText);
// Ajouter tout les elements a la fenetre
this.addWidgets();
// ajouter le panel a la fenetre
frame.getContentPane().add(panel, BorderLayout.CENTER);
// Afficher la fenetre
frame.pack();
frame.setVisible(true);
}
static int fenetreFermeture() {
return JOptionPane.showConfirmDialog(
null,
"Are you sure you wanna quit?",
"Quitter",
JOptionPane.YES_NO_OPTION);
}
private void addWidgets() {
jlabel = new JLabel(new ImageIcon("/Users/momof/eclipse-workspace/chat/src/images/panda.png"), JLabel.CENTER);
texte = new JLabel("Bienvenue sur ce magnifique chat " + agent.getUser().getPseudo());
texte.setFont(new Font("Century Schoolbook", Font.PLAIN, 40));
texte.setHorizontalAlignment(SwingConstants.CENTER);
liste = new JLabel("Active users", JLabel.LEFT);
JMenu contenu = new JMenu("Actions");
contenu.setForeground(Color.BLUE);
contenu.setHorizontalAlignment(SwingConstants.CENTER);
JButton refresh = new JButton("Refresh");
refresh.setForeground(Color.GRAY);
refresh.setHorizontalAlignment(SwingConstants.CENTER);
//JMenuItem usersActifs = new JMenuItem("Active users");
JMenuItem modifierPseudo = new JMenuItem("Modify your pseudo");
JMenuItem deco = new JMenuItem("Deconnection");
//contenu.add(usersActifs);
contenu.add(modifierPseudo);
contenu.add(deco);
menu.add(contenu);
menu.add(refresh);
frame.setJMenuBar(menu);
/*liste déroulante des utilsateurs actifs,
* cliquer dessus pour créer une fenêtre de chat*/
JTextArea ta = new JTextArea(20,20);
ta.insert("Active users\n",0);
JScrollPane scrollPane = new JScrollPane(ta);
String users = agent.getList().actifUsers();
Vector<String> v = new Vector<String>();
for(String pseudo : users.split("\n")) {
v.add(pseudo);
}
JComboBox cb = new JComboBox(v);
cb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Object selected = cb.getSelectedItem();
int idDest = agent.getDb().getIdFromPseudo(selected.toString());
try {
agent.createChat(idDest, selected.toString());
} catch (IOException e) {
System.out.println("Creation tcp chat impossible");
e.printStackTrace();
}
new FenetreChat(agent, selected.toString());
}
});
/*actions pour refresh*/
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String users = agent.getList().actifUsers();
for(String pseudo : users.split("\n")) {
if (!v.contains(pseudo)) {
v.add(pseudo);
}
}
JComboBox cb = new JComboBox(v);
cb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Object selected = cb.getSelectedItem();
int idDest = agent.getDb().getIdFromPseudo(selected.toString());
try {
agent.createChat(idDest, selected.toString());
} catch (IOException e) {
System.out.println("Creation tcp chat impossible");
e.printStackTrace();
}
new FenetreChat(agent, selected.toString());
}
});
}});
frame.getContentPane().add(refresh, BorderLayout.NORTH);
panel.add(BorderLayout.CENTER, jlabel);
panel.add(BorderLayout.SOUTH , texte );
panel.add(BorderLayout.WEST, cb);
/*actions pour modifier le pseudo*/
modifierPseudo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JLabel Text = new JLabel("Enter your new pseudo", SwingConstants.CENTER);
JTextField field = new JTextField(2);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
new FenetreMenu(agent);
}});
JButton ok = new JButton("Continue");
frame.getRootPane().setDefaultButton(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newPseudo = field.getText();
if(agent.changerPseudo(newPseudo)) {
JOptionPane.showMessageDialog(frame, "Your new pseudo is "+newPseudo);
frame.dispose();
new FenetreMenu(agent);
}else {
JOptionPane.showMessageDialog(frame, "Pseudo already, use choose another one");
};
}
});
JPanel panel1 = new JPanel(new GridLayout(4,1));
panel1.add(cancel);
panel1.add(Text);
panel1.add(field);
panel1.add(ok);
frame.getContentPane().removeAll();
frame.getContentPane().add(panel1,BorderLayout.CENTER);
frame.setVisible(true);
}
});
deco.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
agent.deconnexion();
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
} catch (IOException e1) {
System.out.println("Deconnexion impossible");
e1.printStackTrace();
}
}
});
//panel.add(BorderLayout.NORTH, menu);
}
}

Visa fil

@ -0,0 +1 @@
package gui;

Binär
chat/src/gui/panda.png Normal file

Binary file not shown.

Efter

Bredd:  |  Höjd:  |  Storlek: 5,8 KiB

Binär
chat/src/images/panda.png Normal file

Binary file not shown.

Efter

Bredd:  |  Höjd:  |  Storlek: 5,8 KiB

Visa fil

@ -0,0 +1,66 @@
package model;
import java.io.*;
import java.net.InetAddress;
public class Contact {
private String pseudo;
private String status;
private int port;
private int id;
private InetAddress address;
public Contact(String pseudo, InetAddress address, int port) {
this.pseudo = pseudo;
this.address = address;
this.status = "";
this.port = port;
}
public String getPseudo() {
return this.pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public InetAddress getAddress() {
return this.address;
}
public void setAddress(InetAddress address) {
this.address = address;
}
public String getStatut() {
return this.status;
}
public void setStatut(String status) {
this.status = status;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "Pseudo : " + pseudo + " status : " + status + " \n";
}
}

Visa fil

@ -0,0 +1,96 @@
package model;
import network.*;
import java.net.InetAddress;
import java.util.ArrayList;
public class ListeContacts {
private static Contact user;
private ArrayList<Contact> listeContact;
//la liste doit être un singleton
private static final ListeContacts instance = new ListeContacts();
public ListeContacts() {
this.listeContact = new ArrayList<Contact>();
}
public static final ListeContacts getInstance() {
return instance;
}
public static void createUser(String pseudo, int port) {
user = new Contact(pseudo, Tools.getLocalIp(), port);
}
public boolean contactExist(Contact contact) {
for(Contact c : listeContact) {
if(c.getPseudo().equals(contact.getPseudo())){
return true;
}
}
return false;
}
public boolean pseudoExist(String pseudo) {
for(Contact c : listeContact) {
if(c.getPseudo().equals(pseudo)){
return true;
}
}
return false;
}
public void addContact(Contact contact) {
if(!contactExist(contact)){
System.out.println("Pseudo : "+contact.getPseudo()+" ajouté\n");
listeContact.add(contact);
}
}
public void deleteContact(Contact contact) {
if(contactExist(contact)){
System.out.println("Pseudo : "+contact.getPseudo()+"supprimé\n");
listeContact.remove(contact);
}
}
public int length() {
int n = 0;
while(!listeContact.isEmpty()) {
n++;
}
return n;
}
public Contact findContact(String pseudo) {
Contact contact = null;
for(Contact c : listeContact) {
if(c.getPseudo().equals(pseudo)){
contact = c;
break;
}
}
return contact;
}
public String actifUsers() {
String users = "";
for(Contact c : this.listeContact) {
users += (c.getPseudo()+"\n");
}
return users;
}
public ArrayList<Contact> getListe() {
return listeContact;
}
public void setListeContact(ArrayList<Contact> listeContact) {
this.listeContact = listeContact;
}
}

Visa fil

@ -0,0 +1,75 @@
package model;
import java.io.Serializable;
import java.net.*;
public class Message implements Serializable{
protected InetAddress addressSrc;
protected InetAddress addressDest;
protected int portSrc;
protected int portDest;
protected int typeMessage;
public Message(InetAddress addressSrc, InetAddress addressDest, int portSrc, int portDest, int typeMessage) {
this.addressSrc = addressSrc;
this.addressDest = addressDest;
this.portSrc = portSrc;
this.portDest = portDest;
this.typeMessage = typeMessage;
}
public InetAddress getAddressSrc() {
return addressSrc;
}
public void setAddressSrc(InetAddress addressSrc) {
this.addressSrc = addressSrc;
}
public InetAddress getAddressDest() {
return addressDest;
}
public void setAddressDest(InetAddress addressDest) {
this.addressDest = addressDest;
}
public int getPortSrc() {
return portSrc;
}
public void setPortSrc(int portSrc) {
this.portSrc = portSrc;
}
public int getPortDest() {
return portDest;
}
public void setPortDest(int portDest) {
this.portDest = portDest;
}
public int getTypeMessage() {
return typeMessage;
}
public void setTypeMessage(int typeMessage) {
this.typeMessage = typeMessage;
}
}

Visa fil

@ -0,0 +1,22 @@
package model;
import java.net.InetAddress;
public class MessageChat extends Message{
private String message;
public MessageChat(InetAddress addressSrc, InetAddress addressDest, int portSrc, int portDest, int typeMessage, String message) {
super(addressSrc, addressDest, portSrc, portDest, typeMessage);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

Visa fil

@ -0,0 +1,26 @@
package model;
import java.net.InetAddress;
public class MessageDeconnexion extends Message{
private String msg;
private String pseudo;
public MessageDeconnexion(InetAddress addressSrc, InetAddress addressDest, int portSrc, int portDest, int typeMessage, String pseudo) {
super(addressSrc, addressDest, portSrc, portDest, typeMessage);
this.pseudo = pseudo;
this.msg = "Deconnexion";
}
public String getPseudo() {
return pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public String getMsg() {
return msg;
}
}

Visa fil

@ -0,0 +1,23 @@
package model;
import java.net.InetAddress;
public class MessagePseudo extends Message{
private String pseudo;
public MessagePseudo(InetAddress addressSrc, InetAddress addressDest, int portSrc, int portDest, int typeMessage,String pseudo) {
super(addressSrc, addressDest, portSrc, portDest, typeMessage);
this.pseudo = pseudo;
}
public String getPseudo() {
return pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
}

Visa fil

@ -0,0 +1,5 @@
module chat {
requires java.desktop;
requires java.sql;
requires mysql.connector.java;
}

Visa fil

@ -0,0 +1,19 @@
package network;
import java.net.*;
import java.util.*;
public class Manager {
private static int port;
private DatagramSocket broadcast;
private HashMap<String, Integer> portMap;
//network
}

Visa fil

@ -0,0 +1,112 @@
package network;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import controller.Agent;
import model.Contact;
import model.MessageChat;
public class TCPChat extends Thread{
private ArrayList<MessageChat> listeMessagesRecu;
private Socket socket;
private int destID;
private PropertyChangeSupport support;
//connexion faite par un autre user
public TCPChat(Socket socket) {
this.socket = socket;
listeMessagesRecu = new ArrayList<MessageChat>();
this.support = new PropertyChangeSupport(this);
this.start();
}
//connexion faite par le user
public TCPChat(Contact destUser, int destID) throws IOException {
this.socket = new Socket(destUser.getAddress(), destUser.getPort());
listeMessagesRecu = new ArrayList<MessageChat>();
this.destID = destID;
this.support = new PropertyChangeSupport(this);
this.start();
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
this.support.addPropertyChangeListener("Msg TCP Recu", pcl);
}
@Override
public void run() {
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
while(true) {
try {
String input = in.readLine();
MessageChat msgRecu = new MessageChat(this.socket.getInetAddress(), this.socket.getLocalAddress(), this.socket.getPort(), this.socket.getLocalPort(), 0, input);
listeMessagesRecu.add(msgRecu);
System.out.println("fire msg tcp recu");
this.support.firePropertyChange("Msg TCP Recu", true, false);
//if (!msgRecu.getMessage().equals(null)) {
System.out.println("Message reçu : "+msgRecu.getMessage() );
//}
} catch (IOException e) {
System.out.println("Création et read du in impossible");
e.printStackTrace();
}
}
} catch (IOException e1) {
System.out.println("pb création in");
e1.printStackTrace();
}
}
public void sendMsg(String message) throws IOException {
PrintWriter out = new PrintWriter(this.socket.getOutputStream(),true);
out.println(message);
System.out.println("Message envoyé : "+message);
}
public MessageChat getMessageRecu() {
return listeMessagesRecu.remove(0);
}
public ArrayList<MessageChat> getListeMessagesRecu() {
return listeMessagesRecu;
}
public void setListeMessagesRecu(ArrayList<MessageChat> listeMessagesRecu) {
this.listeMessagesRecu = listeMessagesRecu;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public int getDestID() {
return destID;
}
public void setDestID(int destID) {
this.destID = destID;
}
}

Visa fil

@ -0,0 +1,61 @@
package network;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class TCPServer extends Thread{
private ServerSocket socket;
private InetAddress address;
private int port;
private ArrayList<TCPChat> listeConnexions;
private PropertyChangeSupport support;
public TCPServer(int port, InetAddress address) throws IOException {
this.socket = new ServerSocket(port, 1000, address);
this.address = address;
this.port = port;
this.listeConnexions = new ArrayList<TCPChat>();
this.support = new PropertyChangeSupport(this);
this.start();
}
public void addPropertyChangeListener(PropertyChangeListener pcl){
this.support.addPropertyChangeListener("session chat demarree",pcl);
}
@Override
public void run() {
Socket link;
try {
link = socket.accept();
TCPChat tcpChat = new TCPChat(link);
this.listeConnexions.add(tcpChat);
this.support.firePropertyChange("session chat demarree", true, false);
//link.close();// A APPELER QUELQUE PART D'AUTRE
} catch (IOException e) {
System.out.println("Socket non créé ou non fermé");
e.printStackTrace();
}
}
public InetAddress getAddress() {
return address;
}
public void setAddress(InetAddress address) {
this.address = address;
}
public TCPChat getConnexionTCPChat() {
return this.listeConnexions.remove(0);
}
}

Visa fil

@ -0,0 +1,69 @@
package network;
import java.net.*;
import java.util.Enumeration;
public class Tools {
public static InetAddress getLocalIp(){
try{
InetAddress address = InetAddress.getLocalHost();
return address;
}
catch (UnknownHostException e){
System.out.println ("Could not find local address!");
}
return null;
}
//Renvoie un tableau d'InetAdress le premier élement est l'adresse locale de la machine le deuxieme l'adresse de broadcast
public static InetAddress[] getAdress() {
Enumeration<NetworkInterface> interfaces = null;
InetAddress localAdress = null;
InetAddress broadcastAddress = null;
InetAddress[] tab = {null,null};
try {
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.getName().equals("wlan3")){
localAdress = networkInterface.getInterfaceAddresses().get(0).getAddress();
tab[0] = localAdress;
broadcastAddress = networkInterface.getInterfaceAddresses().get(0).getBroadcast();
tab[1] = broadcastAddress;
System.out.println("Found adress : " + localAdress);
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return tab;
}
public static void printInterfaces() {
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{
NetworkInterface networkInterface = interfaces.nextElement();
try {
InetAddress adr = networkInterface.getInterfaceAddresses().get(0).getAddress();
if(adr!=null) {
System.out.println(networkInterface.getName() + adr );
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}

Visa fil

@ -0,0 +1,73 @@
package network;
import model.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.*;
import java.util.ArrayList;
public class UDPInput extends Thread{
private DatagramSocket socket;
private ArrayList<MessagePseudo> messageReceived;
private PropertyChangeSupport support;
public UDPInput(InetAddress localAddress, int port) throws SocketException {
this.socket = new DatagramSocket(port, localAddress);
this.socket.setBroadcast(true);
this.messageReceived = new ArrayList<MessagePseudo>();
this.support = new PropertyChangeSupport(this);
}
public ArrayList<MessagePseudo> getListMessage (){
return this.messageReceived;
}
public MessagePseudo getMessage() {
return this.messageReceived.remove(0);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
this.support.addPropertyChangeListener("Msg UDP Recu", pcl);
}
@Override
public void run() {
byte[] buffer = new byte[5000];
while(true) {
DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(inPacket);
} catch (IOException e) {
System.out.println("Packet UDP non reçu\n");
e.printStackTrace();
}
/* Charset charset = StandardCharsets.US_ASCII;
String pseudo = charset.decode(ByteBuffer.wrap(inPacket.getData())).toString();
MessagePseudo msg = new MessagePseudo(null, null, 0, 0, 0, "");
msg.setPseudo(pseudo);*/
ByteArrayInputStream byteInStream = new ByteArrayInputStream(inPacket.getData());
ObjectInputStream objectInStream;
try {
objectInStream = new ObjectInputStream(byteInStream);
MessagePseudo msg = (MessagePseudo) objectInStream.readObject();
messageReceived.add(msg);
System.out.println("fire property change");
this.support.firePropertyChange("Msg UDP Recu", this.messageReceived.size() -1, this.messageReceived.size());
System.out.println("Message reçu, pseudo = "+msg.getPseudo()+" et num port = "+msg.getPortSrc()+"\n");
} catch (IOException e) {
System.out.println("Objet pas créé");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Objet pas lu");
e.printStackTrace();
}
}
}
}

Visa fil

@ -0,0 +1,50 @@
package network;
import model.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.*;
public class UDPOutput {
private Contact user;
private DatagramSocket socket;
private int port;
public UDPOutput(Contact user, int port) throws SocketException {
this.user = user;
this.port = port;
this.socket = new DatagramSocket(port, user.getAddress());
this.socket.setBroadcast(true);
}
public void send(MessagePseudo msg, InetAddress addressDest, int portSrc) throws IOException {
byte[] buffer = "".getBytes();
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutStream = new ObjectOutputStream(byteOutStream);
objectOutStream.writeObject(msg);
objectOutStream.close();
buffer = byteOutStream.toByteArray();
DatagramPacket packet = new DatagramPacket(buffer,buffer.length,msg.getAddressDest(), msg.getPortDest());
this.socket.send(packet);
System.out.println("Message envoyé, pseudo = "+msg.getPseudo()+" et num port destination = "+portSrc+"\n");
}
public void send(MessageDeconnexion msg, InetAddress addressDest, int portSrc) throws IOException {
byte[] buffer = "".getBytes();
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutStream = new ObjectOutputStream(byteOutStream);
objectOutStream.writeObject(msg);
objectOutStream.close();
buffer = byteOutStream.toByteArray();
DatagramPacket packet = new DatagramPacket(buffer,buffer.length,msg.getAddressDest(),msg.getPortDest());
this.socket.send(packet);
System.out.println("Message envoyé, pseudo = "+msg.getMsg()+" et num port destination = "+portSrc+"\n");
}
}