diff --git a/.gitignore b/.gitignore index 578fff0..d0a2767 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ .settings/ .classpath .project -/bin/ +bin/ diff --git a/README.md b/README.md index cd5d004..ec3acf2 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ -devoir-java +## Chat Application - 2017/03 +This is my first Java project basing on Client-Server structure (with sockets), realised with 3 of my University colleagues. diff --git a/bin/View/Launcher.class b/bin/View/Launcher.class index bd4fb72..3602651 100644 Binary files a/bin/View/Launcher.class and b/bin/View/Launcher.class differ diff --git a/bin/View/MapView.class b/bin/View/MapView.class index d0dc9c2..0d87298 100644 Binary files a/bin/View/MapView.class and b/bin/View/MapView.class differ diff --git a/bin/carte.png b/bin/carte.png deleted file mode 100644 index e7c4c15..0000000 Binary files a/bin/carte.png and /dev/null differ diff --git a/bin/client/Client.class b/bin/client/Client.class index 266dfd5..c05f89f 100644 Binary files a/bin/client/Client.class and b/bin/client/Client.class differ diff --git a/bin/server/Server.class b/bin/server/Server.class index dcb6a11..f7a5314 100644 Binary files a/bin/server/Server.class and b/bin/server/Server.class differ diff --git a/bin/server/ServerThread.class b/bin/server/ServerThread.class deleted file mode 100644 index f5ab81e..0000000 Binary files a/bin/server/ServerThread.class and /dev/null differ diff --git a/res/carte.png b/res/carte.png deleted file mode 100644 index e7c4c15..0000000 Binary files a/res/carte.png and /dev/null differ diff --git a/src/View/ClientUI.java b/src/View/ClientUI.java new file mode 100644 index 0000000..1eac9d0 --- /dev/null +++ b/src/View/ClientUI.java @@ -0,0 +1,142 @@ +package View; + +import java.util.ArrayList; +import java.util.Observable; +import java.util.Observer; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.IOException; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; + +import client.*; +import utils.ImagePanel; + +/** + * ClientUI is the user interface. Each ClientUI create and observe a new Client. + * @author Corentin, Raphael + */ +public class ClientUI extends JFrame implements Observer{ + + private JTextArea textArea; + private JTextField inputTextField; + private JButton sendButton; + private Client client; + private Box boxUsers; + + public ClientUI(Client client) throws IOException { + this.client = client; + // Client is observed by ClientUI + client.addObserver(this); + createUI(); + } + + /** Build user interface + * @throws IOException */ + private void createUI() throws IOException { + + JFrame map = new MapView(this.client); + ImagePanel mapPanel = (ImagePanel) map.getContentPane(); + mapPanel.setBorder(BorderFactory.createLineBorder(Color.black)); + add(mapPanel,BorderLayout.NORTH); + + textArea = new JTextArea(20, 50); + textArea.setEditable(false); + textArea.setLineWrap(true); + add(new JScrollPane(textArea), BorderLayout.CENTER); + + Box box = Box.createHorizontalBox(); + boxUsers = Box.createVerticalBox(); + boxUsers.setBorder(BorderFactory.createLineBorder(Color.black)); + add(box, BorderLayout.SOUTH); + add(new JScrollPane(boxUsers), BorderLayout.EAST); + inputTextField = new JTextField(); + sendButton = new JButton("Send"); + sendButton.setBackground(new Color(59,89,182)); + sendButton.setForeground(Color.WHITE); + sendButton.setFocusPainted(false); + inputTextField.setBackground(new Color(225,225,225)); + inputTextField.setForeground(Color.BLACK); + box.add(inputTextField); + box.add(sendButton); + + // Send text line message to client + ActionListener sendListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + String str = inputTextField.getText(); + if (str != null && str.trim().length() > 0) + client.send(str); + inputTextField.selectAll(); + inputTextField.requestFocus(); + inputTextField.setText(""); + } + }; + inputTextField.addActionListener(sendListener); + sendButton.addActionListener(sendListener); + + this.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + client.close(); + } + }); + + } + + /** Updates the UI depending on the Object argument */ + public void update(Observable o, Object arg) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + textArea.append(arg.toString()); + textArea.append("\n"); + boxUsers.removeAll(); + JLabel titre = new JLabel("Liste des utilisateurs connectés : "); + boxUsers.add(titre); + ArrayList clientsList = client.getClientsData(); + for (Client c : clientsList) { + if(c != null){ + JLabel userName = new JLabel(c.getName()); + boxUsers.add(userName); + } + } + System.out.println("ClientUI update : " + clientsList); + } + }); + } + + public static void main(String[] args) throws IOException { + Client client = new Client(); + + JFrame frame = new ClientUI(client); + frame.setTitle("Chat"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setResizable(false); + frame.setVisible(true); + + String server = "localhost"; + int port = 28000; + try { + client.InitSocket(server,port); + + } catch (IOException e) { + System.out.println("Error while connecting to " + server + ":" + port); + e.printStackTrace(); + System.exit(0); + } + } +} diff --git a/src/View/GridView.java b/src/View/GridView.java index 9ff2b43..9f903db 100644 --- a/src/View/GridView.java +++ b/src/View/GridView.java @@ -1,10 +1,12 @@ package View; +import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; +import java.awt.image.RenderedImage; import java.io.File; import javax.imageio.ImageIO; @@ -14,6 +16,7 @@ import javax.swing.JPanel; import javax.swing.TransferHandler; +import client.Client; import model.GridCase; import model.MapManager; import utils.ImagePanel; @@ -26,20 +29,31 @@ public class GridView extends JPanel { private MapManager mapManager; + + /** Draw borders for the client scope */ + /* + public void paintComponent(Graphics g){ + super.paintComponent(g); + g.drawOval(-200, -200, 400, 400); + //g.drawRect(-200, -200, 400, 400); + //g.drawRoundRect(000, -200, 400, 400,100,100); + + // TODO :: La portée est affichée en brut ici, à changer dynamiquement ! + }*/ - public GridView(MapManager mapManager) { + public GridView(MapManager mapManager, Client currentClient) { super(); this.mapManager = mapManager; // Image du marqueur - ImageIcon pinIcon = new ImageIcon("/Users/bastiensebire/Documents/Work/devoir-java/res/pin.png"); // load the image to a imageIcon + ImageIcon pinIcon = new ImageIcon(getClass().getResource("/res/pin.png")); // load the image to a imageIcon Image pin = pinIcon.getImage(); // transform it Image newPin = pin.getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way pinIcon = new ImageIcon(newPin); // transform it back // Listener permettant de gérer le drag n drop MouseListener ml = new MouseListener() { - + @Override public void mouseClicked(MouseEvent e) {} @@ -48,17 +62,25 @@ public void mousePressed(MouseEvent e) { GridCase jc = (GridCase)e.getSource(); TransferHandler th = jc.getTransferHandler(); + + currentClient.sendPosition(); // Permet d'éviter de pouvoir déplacer une case vide if(jc.getIcon() != null) th.exportAsDrag(jc, e, TransferHandler.COPY); - } @Override public void mouseReleased(MouseEvent e) { GridCase jc = (GridCase)e.getSource(); + // Calcul de la nouvelle position du client + currentClient.setX(jc.getPosition() % mapManager.getSize()); + currentClient.setY(jc.getPosition() / mapManager.getSize()); + currentClient.sendPosition(); + + //System.out.println(currentClient); + // Évite de dupliquer les marqueurs jc.setIcon(null); } @@ -87,14 +109,20 @@ public void mouseExited(MouseEvent e) {} // On ajoute un marqueur pour le client // @TODO placer le marqueur d'un utilisateur venant de se connecter aléatoirement sur la grille - GridCase pinCase = new GridCase(3); + GridCase pinCase = new GridCase(0); + + // Calcul de la position initiale du client + currentClient.setX(pinCase.getPosition() % mapManager.getSize()); + currentClient.setY(pinCase.getPosition() / mapManager.getSize()); + pinCase.setIcon(pinIcon); pinCase.setSize(200, 200); pinCase.addMouseListener(ml); pinCase.setHorizontalTextPosition(JLabel.CENTER); pinCase.setTransferHandler(new TransferHandler("icon")); - add(pinCase, 3); + //pinCase.paintComponent(getGraphics()); + add(pinCase, 0); } public MapManager getMapManager() { diff --git a/src/View/Launcher.java b/src/View/Launcher.java index 56895c6..485aa12 100644 --- a/src/View/Launcher.java +++ b/src/View/Launcher.java @@ -55,7 +55,7 @@ public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == valid) { this.dispose(); - new Client("localhost", 28000,name.getText()); + //new Client("localhost", 28000,name.getText()); } if (e.getSource() == quit) { this.dispose(); diff --git a/src/View/MapView.java b/src/View/MapView.java index c82913e..b8d04da 100644 --- a/src/View/MapView.java +++ b/src/View/MapView.java @@ -31,9 +31,10 @@ public class MapView extends JFrame private MapManager mapManager; private GridView gridView; private Client currentClient; - public MapView() throws IOException + public MapView(Client currentClient) throws IOException { super("La dinde"); + this.currentClient = currentClient; // Configuration de la JFrame setLayout(null); @@ -42,23 +43,18 @@ public MapView() throws IOException setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // On met l'image de la carte en backbground - BufferedImage myImage = ImageIO.read(new File("/Users/bastiensebire/Documents/Work/devoir-java/res/carte.png")); + BufferedImage myImage = ImageIO.read(getClass().getResourceAsStream("/res/carte.png")); setContentPane(new ImagePanel(myImage)); // Déclaration du MapManager et génération de la grille mapManager = new MapManager(10); - gridView = new GridView(mapManager); + gridView = new GridView(mapManager, currentClient); container = this.getContentPane(); container.setLayout(new BorderLayout()); container.add(gridView,BorderLayout.CENTER); container.repaint(); - setVisible(true); - } - - public static void main(String[] args) throws IOException - { - MapView frame = new MapView(); + setVisible(false); } } diff --git a/src/client/Client.java b/src/client/Client.java index c358413..abcea9f 100644 --- a/src/client/Client.java +++ b/src/client/Client.java @@ -1,85 +1,135 @@ package client; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.io.Serializable; import java.net.Socket; +import java.util.ArrayList; +import java.util.Observable; + +import model.Message; -import View.Launcher; /** - * Client allows a user to send messages to the server. - * @author lenaic - * + * Client allows a user to send messages to the server. This class communicates with ClientUI (Obs) and ClientThread with ObjectStream + * This is a serializable class that allow it to be send in ObjectStream (only with position and name) + * @author Corentin */ -public class Client { +public class Client extends Observable implements Serializable { - private Socket socket = null; - private DataInputStream console = null; - private DataOutputStream streamOut = null; + // Serializabled attributes private String name; + private int position_x; + private int position_y; + private ArrayList clientsData = new ArrayList<>(); // Client knows its Client's pair. + + // Sockets and streams attributes + private Socket socket = null; + private OutputStream outputStream; + private ObjectOutputStream objectOutputStream; + + public Client(){ + super(); + } + + /** This constructor is used to send this into socket **/ + public Client(String name, int position_x, int position_y){ + this.name = name; + this.position_x = position_x; + this.position_y = position_y; + } + + /** Create socket, and receiving thread */ + public void InitSocket(String server, int port) throws IOException { + socket = new Socket(server, port); + outputStream = socket.getOutputStream(); + objectOutputStream = new ObjectOutputStream(outputStream); + + Thread receivingThread = new Thread(new ReceivingThread(socket, this)); + receivingThread.start(); + } + + /** ClientUI is updating with arg by this method **/ + public void notifyObservers(Object arg) { + super.setChanged(); + super.notifyObservers(arg); + } + + /** Send a text Message to ClientThread */ + public void send(String text) { + try { + Message message = new Message(Message._TEXT_, text, this.name, this.position_x, this.position_y, null); + objectOutputStream.writeObject(message); + } catch (IOException e) { + notifyObservers(e); + } + } + + /** Send a position Message to ClientThread */ + public void sendPosition() { + try { + Message message = new Message(Message._POSITION_, "", this.name, this.position_x, this.position_y, null); + System.out.println("Client.SendPosition :" +message); + objectOutputStream.writeObject(message); + } catch (IOException e) { + notifyObservers(e); + } + } + + /** Close the socket */ + public void close() { + try { + socket.close(); + Message message = new Message(Message._DISCONNECT_, "", this.name, 0, 0, null); + objectOutputStream.writeObject(message); + } catch (IOException ex) { + notifyObservers(ex); + } + } + + /** Getter for the name */ + public String getName() { + return name; + } - /** - * Constructor of the class. - * @param serverName : Host. - * @param serverPort : Port. - * @param name : Name of the user. - */ - public Client(String serverName, int serverPort, String name) { + /** Setter for the name */ + public void setName(String name) { this.name = name; - System.out.println("Connexion en cours ..."); - try - { - socket = new Socket(serverName, serverPort); - System.out.println("Connecté: " + this.name); - this.start(); - } - catch(IOException e) - { - e.printStackTrace(); - } - String line = ""; - while (!line.equals(".bye")) { - try { - line = console.readLine(); - streamOut.writeUTF(this.name +": " + line); - streamOut.flush(); - } - catch(IOException e) - { - e.printStackTrace(); - } - } } - - /** - * Start the communication with the server - * @throws IOException - */ - public void start() throws IOException { - console = new DataInputStream(System.in); - streamOut = new DataOutputStream(socket.getOutputStream()); + + /** Getter for the x position */ + public int getX() { + return position_x; } - - /** - * Stop the communication with the server - */ - public void stop() { - try{ - if (console != null) - console.close(); - if (streamOut != null) - streamOut.close(); - if (socket != null) - socket.close(); - } - catch(IOException e) - { - e.printStackTrace(); - } + + /** Setter for the x position */ + public void setX(int position_x) { + this.position_x = position_x; + } + + /** Getter for the y position */ + public int getY() { + return position_y; + } + + /** Setter for the y position */ + public void setY(int position_y) { + this.position_y = position_y; + } + + public void setClientsData(ArrayList clients){ + this.clientsData = clients; } - public static void main(String args[]) { - new Launcher(); + public ArrayList getClientsData(){ + return clientsData; + } + + @Override + public String toString() { + return "Client [name=" + name + ", position_x=" + position_x + ", position_y=" + position_y + ", clientsData=" + + clientsData + ", socket=" + socket + ", outputStream=" + outputStream + ", objectOutputStream=" + + objectOutputStream + "]"; } } diff --git a/src/client/ClientThread.java b/src/client/ClientThread.java new file mode 100644 index 0000000..3a7b29b --- /dev/null +++ b/src/client/ClientThread.java @@ -0,0 +1,153 @@ +package client; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.Socket; +import java.util.ArrayList; + +import model.Message; +import model.MessageValidator; + +/** + * ClientThread is the thread that communicates with Server and Client. It receives Message from Client and sends Message to Client. + * @author Corentin + */ +public class ClientThread extends Thread{ + // Client Data (Name, posX, posY) saved in thread, not real Client instanced in ClientUI. + private Client clientData; + private ObjectInputStream streamIn = null; + private ObjectOutputStream streamOut = null; + + private Socket clientSocket = null; + private ArrayList threads = new ArrayList(); + + public ClientThread(Socket clientSocket, ArrayList threads) { + this.clientSocket = clientSocket; + this.threads = threads; + } + + public synchronized void run() { + // Each ClientThread knows its ClientThread's pair. + ArrayList threads = this.threads; + + try { + InputStream is = clientSocket.getInputStream(); + ObjectInputStream streamIn = new ObjectInputStream(is); + streamOut = new ObjectOutputStream(clientSocket.getOutputStream()); + + // Ask to Client it's username and save him into clientData + streamOut.writeObject(new Message(Message._TEXT_,"Quel est votre nom ?", "BOT", 0, 0, getClients())); + Message msgName = (Message)streamIn.readObject(); + String clientName = msgName.text; + + this.clientData = new Client(clientName, 0, 0); + + for(ClientThread thread : threads){ + if(thread != this){ + streamOut.writeObject(new Message(Message._TEXT_," s'est connecté !", clientName, 0, 0, getClients())); + } else { + streamOut.writeObject(new Message( Message._NAME_, "Bonjour " + clientName + " et bienvenue dans le chat. Pour communiquer et voir les utilisateurs connectés, il est nécessaire de se positionner à leur portée à l'aide d'un drag and drop", clientName, 0, 0, getClients())); + } + ArrayList clients = getClients(); + } + + /* Start the conversation. */ + while (true) { + ArrayList messages = new ArrayList<>(); + Message msg = (Message)streamIn.readObject(); + messages.add(msg); + if(msg != null){ + switch(msg.type){ + case Message._TEXT_: + sendMessages(messages); + break; + + case Message._DISCONNECT_: + disconnect(); + break; + + case Message._POSITION_: + refreshClientData(msg.clientName, msg.posX, msg.posY); + break; + + default: + System.out.println("test default"); + break; + } + } + } + } catch (IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + + /** This method allows threads to send Messages to every Client **/ + public synchronized void sendMessages(ArrayList messages){ + ArrayList clients = getClients(); + + for(ClientThread thread : threads){ + for(Message message : messages){ + try { + // All clients connected to server are saved into Message to allow Client to know them each other. + message.clients = clients; + /*MessageValidator val = new MessageValidator(this.clientData, thread.clientData); + if(this == thread || val.isClientsNear() == true) + thread.streamOut.writeObject(message); + else + System.out.println("Hors de portée");*/ + thread.streamOut.writeObject(message); + System.out.println("ClientThread.sendMessages :" + message); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + public synchronized void sendMessage(Message message){ + ArrayList messages = new ArrayList<>(); + messages.add(message); + sendMessages(messages); + } + + /** Save Client new position **/ + public synchronized void refreshClientData(String name, int posX, int posY){ + this.clientData.setName(name); + this.clientData.setX(posX); + this.clientData.setY(posY); + + System.out.println(name+" position updated" + clientData); + } + + public synchronized Message createClientsMessage(){ + ArrayList clients = getClients(); + return (new Message(Message._CLIENTS_, clients)); + } + + /** Return the list of Thread's Clients **/ + public ArrayList getClients(){ + ArrayList clients = new ArrayList<>(); + for(ClientThread thread : threads){ + clients.add(thread.clientData); + } + return clients; + } + + public synchronized void disconnect(){ + try{ + for(ClientThread thread : threads){ + thread.streamOut.writeObject(new Message(Message._TEXT_, clientData.getName() + "s'est déconnecté !", "", 0, 0, getClients())); + if(thread == this) + thread = null; + } + + streamIn.close(); + streamOut.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/client/ReceivingThread.java b/src/client/ReceivingThread.java new file mode 100644 index 0000000..f5797eb --- /dev/null +++ b/src/client/ReceivingThread.java @@ -0,0 +1,48 @@ +package client; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.net.Socket; + +import model.Message; + +/** + * ReceivingThread allows Client to listen ClientThread + * @author Corentin + */ +public class ReceivingThread implements Runnable{ + + private Socket socket; + private Client client; + + public ReceivingThread(Socket socket, Client client){ + this.socket = socket; + this.client = client; + } + + public void run() + { + try { + InputStream is = socket.getInputStream(); + ObjectInputStream streamIn = new ObjectInputStream(is); + + Message msg = null; + while(true){ + msg = (Message)streamIn.readObject(); + if(msg.type == Message._NAME_){ + this.client.setName(msg.clientName); + msg.clientName = "BOT"; + } + // Set Clients array to Client + this.client.setClientsData(msg.clients); + // Notify all observers that ClientThread just send a Message + this.client.notifyObservers("<"+msg.clientName+">"+msg.text); + System.out.println("ReceivingThread.run Message :" + msg); + } + + } catch (IOException | ClassNotFoundException e) { + this.client.notifyObservers(e); + } + } +} diff --git a/src/model/GridCase.java b/src/model/GridCase.java index 1f68b14..590bdde 100644 --- a/src/model/GridCase.java +++ b/src/model/GridCase.java @@ -1,5 +1,7 @@ package model; +import java.awt.Graphics; + import javax.swing.JLabel; /** diff --git a/src/model/Message.java b/src/model/Message.java new file mode 100644 index 0000000..2d875bb --- /dev/null +++ b/src/model/Message.java @@ -0,0 +1,48 @@ +package model; + +import java.io.Serializable; +import java.util.ArrayList; + +import client.Client; + +/** + * Message + * @author Corentin + */ +public class Message implements Serializable { + public final static int _NAME_ = 0; + public final static int _TEXT_ = 1; + public final static int _CLIENTS_ = 2; + public final static int _DISCONNECT_ = 3; + public final static int _POSITION_ = 4; + public final static int _CONNECT_ = 5; + + public int type; + public String text; + public String clientName; + public int posX; + public int posY; + + public ArrayList clients; + + public Message(int type, String text, String clientName, int posX, int posY, ArrayList clients){ + this.type = type; + this.text = text; + this.clientName = clientName; + + this.posX = posX; + this.posY = posY; + this.clients = clients; + } + + public Message(int type, ArrayList clients){ + this.type = type; + this.clients = clients; + } + + @Override + public String toString() { + return "Message [type=" + type + ", text=" + text + ", clientName=" + clientName + ", posX=" + posX + ", posY=" + + posY + ", clients=" + clients + "]"; + } +} diff --git a/src/model/MessageValidator.java b/src/model/MessageValidator.java new file mode 100644 index 0000000..8adbca6 --- /dev/null +++ b/src/model/MessageValidator.java @@ -0,0 +1,97 @@ +package model; + +import client.Client; + +/** + * @author Raphael + * + * Check if two clients can communicate + */ +public class MessageValidator { + + private Client client1; + private Client client2; + + /** + * Constructor of the class + * @param c1 : the first client + * @param c2 : the second client + */ + public MessageValidator(Client c1, Client c2) { + this.client1 = c1; + this.client1 = c2; + } + + /** + * Check if the two client is near or not. They are near when they are + * within 4 case of each other. + * @return true if the two client can communicate or false if they can't + */ + public boolean isClientsNear() { + int x1 = this.client1.getX(); + int y1 = this.client1.getY(); + + if (client2 == null) + return true; + int x2 = this.client2.getX(); + int y2 = this.client2.getY(); + // Portée de communication entre deux clients + int scope = 4; + + if(x1 <= x2) { + // Si le client 2 n'est plus à portée du client 1 sur l'axe x + if((x2-x1) > scope) { + return false; + } + } + if(x2 <= x1) { + // Si le client 1 n'est plus à portée du client 2 sur l'axe x + if((x1-x2) > scope) { + return false; + } + } + if(y1 <= y2) { + // Si le client 2 n'est plus à portée du client 1 sur l'axe y + if((y2-y1) > scope) { + return false; + } + } + if(y2 <= y1) { + // Si le client 1 n'est plus à portée du client 2 sur l'axe y + if((y1-y2) > scope) { + return false; + } + } + + return true; + } + + /** + * toSring method + */ + public String toString() { + String s = ""; + if(this.isClientsNear()) { + s += "Les clients" + this.client1.getName() + " et " + this.client2.getName() + " sont à portée de communication"; + } + else { + s += "Les clients" + this.client1.getName() + " et " + this.client2.getName() + " ne sont pas à portée de communication"; + } + return s; + } + + /** + * Test class + * @param args + */ + public static void main(String[] args) { + Client c1 = new Client(); + Client c2 = new Client(); + Client c3 = new Client(); + MessageValidator m1 = new MessageValidator(c1,c2); + MessageValidator m2 = new MessageValidator(c1,c3); + System.out.println("Test de proximité :"); + System.out.println(m1.toString()); + System.out.println(m2.toString()); + } +} \ No newline at end of file diff --git a/src/res/carte.png b/src/res/carte.png new file mode 100644 index 0000000..4d384f5 Binary files /dev/null and b/src/res/carte.png differ diff --git a/res/pin.png b/src/res/pin.png similarity index 100% rename from res/pin.png rename to src/res/pin.png diff --git a/src/server/Server.java b/src/server/Server.java index dd5ffef..47c2220 100644 --- a/src/server/Server.java +++ b/src/server/Server.java @@ -3,90 +3,44 @@ import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; +import java.util.ArrayList; + +import client.ClientThread; /** - * Server allow the communication between many clients. - * @author lenaic + * Server allow the communication between many ClientThread. + * @author Corentin * */ -public class Server implements Runnable { - private ServerSocket server = null; - private Thread thread = null; - private ServerThread client = null; - - /** - * Constructor of the class. - * @param port : Port. - */ - public Server(int port) { - try - { - System.out.println("Connexion au port " + port + ", veuillez patienter ..."); - server = new ServerSocket(port); - System.out.println("Serveur lancé: " + server); - start(); - } - catch(IOException e) - { - e.printStackTrace(); - } - } - - /** - * Waiting for client. - */ - public void run() { - while (thread != null) { - try { - System.out.println("En attente de clients ..."); - this.addThread(server.accept()); - } - catch(IOException e) { - e.printStackTrace(); - } - } - } - - /** - * Add new client. - * @param socket : socket. - */ - public void addThread(Socket socket) { - System.out.println("Client accepté: " + socket); - client = new ServerThread(this, socket); - try { - client.open(); - client.start(); - } - catch(IOException e) - { - e.printStackTrace(); - } - } +public class Server { + private static ServerSocket serverSocket = null; + private static Socket clientSocket = null; - /** - * Start a thread for a client. - */ - public void start() { - if (thread == null) { - thread = new Thread(this); - thread.start(); - } - } - - /** - * Stop a thread for a client. - */ - public void stop() { - if (thread != null) { - thread.stop(); - thread = null; - } - } - - public static void main(String args[]){ - Server server = null; - server = new Server(28000); + private static int port = 28000; + private static ArrayList threads = new ArrayList(); + + public static void main(String args[]) { + + try { + serverSocket = new ServerSocket(port); + System.out.println("Server started at localhost:"+port); + } catch (IOException e) { + System.out.println(e); + } + + /* + * Create a new client socket when a client is connecting + */ + while (true) { + try { + clientSocket = serverSocket.accept(); + ClientThread thread = new ClientThread(clientSocket, threads); + thread.start(); + threads.add(thread); + } catch (IOException e) { + System.out.println(e); + } + } } } diff --git a/src/server/ServerThread.java b/src/server/ServerThread.java deleted file mode 100644 index 8311c9c..0000000 --- a/src/server/ServerThread.java +++ /dev/null @@ -1,62 +0,0 @@ -package server; - - -import java.net.*; -import java.io.*; - -/** - * ServerThread is the communication between client and server. - * @author lenaic - * - */ -public class ServerThread extends Thread { - private Socket socket = null; - private Server server = null; - private int id = -1; - private DataInputStream streamIn = null; - - /** - * Constructor of the class. - * @param server : server. - * @param socket : socket. - */ - public ServerThread(Server server, Socket socket) { - this.server = server; - this.socket = socket; - this.id = socket.getPort(); - } - - /** - * Inform that a new user is connected. - */ - public void run() { - System.out.println("Client " + id + " connecté."); - while (true) - { - try { - System.out.println(streamIn.readUTF()); - } - catch(IOException e) { } - } - } - - /** - * Open the discussion channel. - * @throws IOException - */ - public void open() throws IOException { - streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream())); - } - - /** - * Close the discussion channel. - * @throws IOException - */ - public void close() throws IOException { - if (socket != null) - socket.close(); - if (streamIn != null) - streamIn.close(); - } - -} pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy