ClypeClient.
java
 1 package main;
 2
 3 import java.io.IOException;
20
21 public class ClypeClient extends Thread {
22
23     private String userName, hostName;
24     private int port;
25     private boolean closeConnection;
26     private ClypeData dataToSendToServer;
27     private ClypeData dataToReceiveFromServer;
28     private ObjectInputStream inFromServer;
29     private ObjectOutputStream outToServer;
30
31     private final String key = "KEY";
32
33     static final int DEFAULT_PORT = 7000;
34
35     private GUI gui;
36
37     private int id;
38
39
40     /**
41       *
42       * Constructor that initializes userName, hostName, port, closeConnection,
   dataToSendToServer, dataToReceiveFromServer.
43       *
44       * This constructor takes a the username of the client, the hostname of the client, and
   the port the client uses.
45       *
46       * @param userName Username of the client
47       * @param hostName Hostname of the client
48       * @param port Port the client uses
49       * @throws IllegalArgumentException makes sure username hostname arent null and port is
   not less than 1024
50       */
51     public ClypeClient(GUI gui, String userName, String hostName, int port) throws
   IllegalArgumentException {
52          if(userName == null || hostName == null || port < 1024)
53              throw new IllegalArgumentException();
54          this.userName = userName;
55          this.hostName = hostName;
56          this.port = port;
57          closeConnection = false;
58          dataToSendToServer = null;
59          dataToReceiveFromServer = null;
60          inFromServer = null;
61          outToServer = null;
62          this.gui = gui;
63          id = -1;
64     }
65
66     /**
67       *
68       * Constructor that calls parent constructor which only takes a username and a hostname
69       * and defaults the port to 7000
70       *
71       * @param userName Username of the client
                                   ClypeClient.java
 72      * @param hostName Hostname of the client
 73      */
 74    public ClypeClient(GUI gui, String userName, String hostName) {
 75         this(gui, userName, hostName, DEFAULT_PORT);
 76    }
 77
 78    /**
 79      * Constructor that calls parent constructor and only takes a username
 80      * and defaults the hostname to "localhost" and sets the port to 7000
 81      *
 82      * @param userName Username of the client
 83      */
 84    public ClypeClient(GUI gui, String userName) {
 85         this(gui, userName, "localhost");
 86    }
 87
 88    /**
 89      *
 90      * Constructor that calls parent constructor, this is also the default constructor.
 91      * This constructor defaults the username to "Anonymous", the hostname to "localhost",
 92      * and sets the port to 7000.
 93      *
 94      */
 95    public ClypeClient(GUI gui) {
 96         this(gui, "Anonymous");
 97    }
 98
 99     /**
100      * Method that initializes the scanner that reads in from standard input, then while the
    connection is open,
101      * this function reads the client data and the prints that data to the standard output.
102      */
103     public void run() {
104
105         try {
106
107             Socket skt = new Socket(this.hostName, this.port);
108
109             //BufferedReader is = new BufferedReader(new
    InputStreamReader(skt.getInputStream()));
110             outToServer = new ObjectOutputStream(skt.getOutputStream());
111             inFromServer = new ObjectInputStream(skt.getInputStream());
112
113             ClientSideServerListener cl = new ClientSideServerListener(this);
114             Thread listener = new Thread(cl);
115
116             listener.start();
117
118             synchronized(this) {
119
120                 GUI.send = true;
121                 dataToSendToServer = new MessageClypeData(userName, "", ClypeData.GET_ID, id);
122                 sendData();
123
124                 GUI.send = true;
125                 dataToSendToServer = new MessageClypeData(userName, "",
    ClypeData.GET_CONNECTED, id);
126                 sendData();
127
                                    ClypeClient.java
128              }
129
130              while(!closeConnection) {
131                  readClientData();
132                  sendData();
133              }
134
135              inFromServer.close();
136              outToServer.close();
137              skt.close();
138        }   catch (UnknownHostException e) {
139              System.err.println("Unknown Host: " + e.getMessage());
140        }   catch (NoRouteToHostException e) {
141              System.err.println("Server unreachable " + e.getMessage());
142        }   catch (ConnectException e) {
143              System.err.println("Connection refused: " + e.getMessage());
144        }   catch (IOException e) {
145              System.err.println(e.getMessage());
146        }
147
148    }
149
150
151    /**
152     *
153     * Reads client data and initiializes dataToSendToServer
154     *
155     * Takes the following commands:
156     *
157     * DONE - closes clients connection
158     * SENDFILE filename.txt - sends a file
159     * LISTUSERS - lists all the users
160     *
161     *
162     */
163    public synchronized void readClientData() {
164
165        //if(this.closeConnection)
166        // return;
167        if(GUI.send) {
168
169        String input = gui.getText();
170
171        switch(input.indexOf(" ") != -1 ? input.substring(0, input.indexOf(" ")) : input) {
172
173        case "DONE":
174            dataToSendToServer = new MessageClypeData(userName, "DONE", ClypeData.LOGOUT, id);
175            break;
176        case "SENDFILE":
177
178              FileClypeData file = null;
179
180             try {
181                 file = new FileClypeData(userName, input.substring(input.indexOf(" ") + 1,
    input.length()), ClypeData.SEND_FILE, id);
182                 file.readFileContents();
183             } catch (IOException e) {
184                 file = null;
185                 System.err.println(e.getMessage());
                                    ClypeClient.java
186              }
187
188              dataToSendToServer = file;
189
190              break;
191          case "LISTUSERS":
192              //list users to this client
193              dataToSendToServer = new MessageClypeData(userName, input, ClypeData.ALLUSERS,
      id);
194              break;
195          default:
196              dataToSendToServer = new MessageClypeData(userName, input, ClypeData.SEND_MESSAGE,
      id);
197              break;
198
199          }
200          } else if(GUI.sendPicture) {
201
202              String input = gui.getText();
203              PictureClypeData pic = new PictureClypeData(userName, input,
    ClypeData.SEND_PICTURE, id);
204              pic.createPicture();
205              dataToSendToServer = pic;
206
207          }
208     }
209
210     public void close() {
211          GUI.send = true;
212          dataToSendToServer = new MessageClypeData(userName, "DONE", ClypeData.LOGOUT, id);
213     }
214
215     /**
216       * Sends data to the server
217       */
218     public synchronized void sendData() {
219
220          try {
221              if(GUI.send) {
222                  GUI.send = false;
223
224                  if(dataToSendToServer.getType() == ClypeData.LOGOUT) {
225                      this.closeConnection = true;
226                      gui.close();
227                  }
228
229                  outToServer.writeObject(dataToSendToServer);
230
231              }
232
233              if(GUI.sendPicture) {
234                  GUI.sendPicture = false;
235
236                  outToServer.writeObject(dataToSendToServer);
237              }
238
239          } catch (IOException e) {
240              // TODO Auto-generated catch block
241              System.err.println("LAUGHS: " + e.getMessage());
                                  ClypeClient.java
242            closeConnection = true;
243        }
244
245    }
246    /**
247      * Recieves data from the server
248      */
249    public void receiveData() {
250
251        try {
252
253            if(!closeConnection) {
254
255                dataToReceiveFromServer = (ClypeData) inFromServer.readObject();
256
257                if(dataToReceiveFromServer.getType() == ClypeData.GET_ID) {
258
259                    if(this.id == -1)
260                        this.id = Integer.parseInt((String)dataToReceiveFromServer.getData());
261
262                    //System.out.println("ID: " + this.id);
263
264                }
265
266            }
267
268        } catch (ClassNotFoundException | IOException e) {
269            // TODO Auto-generated catch block
270            System.err.println("HI: " + e.getMessage());
271            closeConnection = true;
272
273        }
274
275    }
276    /**
277      * Method that prints all of the clients data
278      */
279    public void printData() {
280
281         try {
282             if(dataToReceiveFromServer.getClientID() != this.id) {
283                      if(dataToReceiveFromServer.getType() != ClypeData.GET_ID &&
    dataToReceiveFromServer.getType() != ClypeData.SEND_PICTURE &&
    dataToReceiveFromServer.getType() != ClypeData.LOGOUT && dataToReceiveFromServer.getType() !=
    ClypeData.ALLUSERS && dataToReceiveFromServer.getType() != ClypeData.GET_CONNECTED) {
284                          System.out.println("Username: " + this.getUserName() + "\n"
285                                  + "Recieved Data:\n" +
    this.dataToReceiveFromServer.getDataToPrint() + "\n" + "Sender: " +
    dataToReceiveFromServer.getClientID());
286                          gui.setLabel("Client " + this.dataToReceiveFromServer.getClientID() +
    ": " + this.dataToReceiveFromServer.getData());
287                      } else if(dataToReceiveFromServer.getType() == ClypeData.SEND_PICTURE) {
288                          Image b = (Image) dataToReceiveFromServer.getData();
289                          ImageView view = new ImageView(b);
290                          gui.addPicture(view);
291                      }
292
293             } else {
294                 if(dataToReceiveFromServer.getType() == ClypeData.ALLUSERS) {
                                     ClypeClient.java
295                       gui.setLabel("All Connected Users: " +
    this.dataToReceiveFromServer.getData());
296                  }
297                  gui.clearText();
298              }
299
300              if (dataToReceiveFromServer.getType() == ClypeData.GET_CONNECTED) {
301                  gui.removeAllFriends();
302                  String lines[] = ((String)dataToReceiveFromServer.getData()).split("\\n");
303                  for(String l : lines)
304                       gui.addFriend(l.substring(0,l.lastIndexOf('.')),
    Integer.parseInt(l.substring(l.lastIndexOf('.')+1, l.length())));
305              }
306
307              if (dataToReceiveFromServer.getType() == ClypeData.LOGOUT) {
308                  gui.removeAllFriends();
309                  String lines[] = ((String)dataToReceiveFromServer.getData()).split("\\n");
310                  for(String l : lines)
311                       gui.addFriend(l.substring(0,l.lastIndexOf('.')),
    Integer.parseInt(l.substring(l.lastIndexOf('.')+1, l.length())));
312              }
313
314          } catch (NullPointerException e) {
315              //laugh
316          }
317
318     }
319
320     /**
321       *
322       * Getter method for userName
323       *
324       * @return the username of the client
325       */
326     public String getUserName() {
327          return userName;
328     }
329
330     /**
331       *
332       * Getter method for hostName
333       *
334       * @return the hostname of the client
335       */
336     public String getHostName() {
337          return hostName;
338     }
339
340     /**
341       *
342       * Getter method for port
343       *
344       * @return the port the client uses
345       */
346     public int getPort() {
347          return port;
348     }
349
350     /**
                                    ClypeClient.java
351      * @return if the connection is closed or not
352      */
353    public boolean isClosed() {
354         return closeConnection;
355    }
356
357    public int getID() {
358        return id;
359    }
360
361     /**
362       *
363       * Overriden method of the equals method. Checks to see whether two ClypeClient's are the
    same,
364       * which is done by checking if the following are equal: userName, hostName, port,
    closeConnection.
365       *
366       * Also makes sure obj is not null and is of type ClypeClient
367       *
368       * @param obj which should be of type ClypeClient
369       */
370     @Override
371     public boolean equals(Object obj) {
372          if(this == obj)
373               return true;
374          if(obj == null || !(obj instanceof ClypeClient))
375               return false;
376
377          ClypeClient c = (ClypeClient) obj;
378          if(c.getUserName() == this.getUserName() && c.getHostName() == this.getHostName() &&
    c.getPort() == this.getPort()
379                   && c.closeConnection == this.closeConnection)
380               return true;
381          else
382               return false;
383     }
384
385     /**
386       *
387       * Overriden method of hashCode().
388       *
389       *
390       */
391     @Override
392     public int hashCode() {
393          //from lecture notes
394          int result = 17;
395          if(this.getUserName() != null)
396          result = 37*result + this.getUserName().hashCode();
397          if(this.getHostName() != null)
398          result = 37*result + this.getHostName().hashCode();
399          result = 37*result + this.getPort();
400          if(this.dataToSendToServer != null)
401          result = 37*result + this.dataToSendToServer.hashCode();
402          if(this.dataToReceiveFromServer != null)
403          result = 37*result + this.dataToReceiveFromServer.hashCode();
404          return result;
405     }
406
                                    ClypeClient.java
407     /**
408       *
409       *
410       * Overriden method that makes sure the client object can be printed out and prints the
    following:
411       * Username, Hostname, Port, Wheter or not the connection is closed, The data to send to
    server,
412       * The Data to be recieved from the server.
413       */
414     @Override
415     public String toString() {
416
417          return "Username: " + this.getUserName() + "\n"
418                  + "Host Name: " + this.getHostName() + "\n"
419                  + "Port: " + this.getPort() + "\n"
420                  + "Connection is closed: " + this.closeConnection + "\n"
421                  + "Data to send: " + this.dataToSendToServer + "\n"
422                  + "Data to recieve: " + this.dataToReceiveFromServer + "\n";
423
424     }
425
426 }
427