Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that enables two users to chat using JavaFX, threads, sockets. I

ID: 3829883 • Letter: W

Question

Write a program that enables two users to chat using JavaFX, threads, sockets. Implement one user as the server and the other as the client. The server has two text areas: One for entering text and the other(non editable) for displaying text received from the client. When the user presses the enter key. the current line is send to the client. The client too has two text areas: One for entering text and the other (non editable) for displaying text received from the server. When the user presses the enter key, the current line is send to the server.

Explanation / Answer

import java.io.*;

public class ChatMessage implements Serializable {

        protected static final long serialVersionUID = 1112122200L;

        static final int WHOISIN = 0, MESSAGE = 1, LOGOUT = 2;

        private int type;

        private String message;

               

        ChatMessage(int type, String message) {

               this.type = type;

               this.message = message;

        }      

                            int getType() {

               return type;

        }

        String getMessage() {

               return message;

        }

}

Server.java

import java.io.*;

import java.net.*;

import java.text.SimpleDateFormat;

import java.util.*;

public class Server {

       

        private static int uniqueId;

       

        private ArrayList<ClientThread> al;

       

        private ServerGUI sg;

                private SimpleDateFormat sdf;

       

        private int port;

       

        private boolean keepGoing;

        public Server(int port) {

               this(port, null);

        }

       

        public Server(int port, ServerGUI sg) {

              

               this.sg = sg;

               this.port = port;

               sdf = new SimpleDateFormat("HH:mm:ss");

               al = new ArrayList<ClientThread>();

        }

       

        public void start() {

               keepGoing = true;             

               try

               {             

                       ServerSocket serverSocket = new ServerSocket(port);

                      

                       while(keepGoing)

                       {

                               display("Server waiting for Clients on port " + port + ".");

                              

                               Socket socket = serverSocket.accept();

                              

                               if(!keepGoing)

                                      break;

                               ClientThread t = new ClientThread(socket);                          al.add(t);                                                                  // save it in the ArrayList

                               t.start();

                       }       try {

                               serverSocket.close();

                               for(int i = 0; i < al.size(); ++i) {

                                      ClientThread tc = al.get(i);

                                      try {

                                      tc.sInput.close();

                                      tc.sOutput.close();

                                      tc.socket.close();

                                      }

                                      catch(IOException ioE) {

                                             

                                      }}}

                       catch(Exception e) {

                               display("Exception closing the server and clients: " + e);

                       }}

                              catch (IOException e) {

            String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + " ";

                       display(msg);

               }

        }             

        protected void stop() {

               keepGoing = false;            

               try {

                       new Socket("localhost", port);

               }

               catch(Exception e) {

                                      }

        }      

        private void display(String msg) {

               String time = sdf.format(new Date()) + " " + msg;

               if(sg == null)

                       System.out.println(time);

               else

                       sg.appendEvent(time + " ");

        }      

        private synchronized void broadcast(String message) {

                              String time = sdf.format(new Date());

               String messageLf = time + " " + message + " ";

                              if(sg == null)

                       System.out.print(messageLf);

               else

                       sg.appendRoom(messageLf);           

              

               for(int i = al.size(); --i >= 0;) {

                       ClientThread ct = al.get(i);

                       if(!ct.writeMsg(messageLf)) {

                               al.remove(i);

                               display("Disconnected Client " + ct.username + " removed from list.");

                       }}}    

        synchronized void remove(int id) {           

               for(int i = 0; i < al.size(); ++i) {

                       ClientThread ct = al.get(i);

                               if(ct.id == id) {

                               al.remove(i);

                               return;

                       }}}

       

        public static void main(String[] args) {

                              int portNumber = 1500;

               switch(args.length) {

                       case 1:

                               try {

                                      portNumber = Integer.parseInt(args[0]);

                               }

                               catch(Exception e) {

                                      System.out.println("Invalid port number.");

                                      System.out.println("Usage is: > java Server [portNumber]");

                                      return;

                               }

                       case 0:

                               break;

                       default:

                               System.out.println("Usage is: > java Server [portNumber]");

                               return;                       

               }             

               Server server = new Server(portNumber);

               server.start();

        }      

        class ClientThread extends Thread {          

               Socket socket;

               ObjectInputStream sInput;

               ObjectOutputStream sOutput;

                              int id;       

               String username;              

               ChatMessage cm;       

               String date;

               ClientThread(Socket socket) {

                                              id = ++uniqueId;

                       this.socket = socket;                

                       System.out.println("Thread trying to create Object Input/Output Streams");

                       try

                       {sOutput = new ObjectOutputStream(socket.getOutputStream());

                               sInput = new ObjectInputStream(socket.getInputStream());                    

                               username = (String) sInput.readObject();

                               display(username + " just connected.");

                       }

                       catch (IOException e) {

                               display("Exception creating new Input/output Streams: " + e);

                               return;

                       }

                       catch (ClassNotFoundException e) {

                       }

            date = new Date().toString() + " ";

               }

              

               public void run() {

                      

                       boolean keepGoing = true;

                       while(keepGoing) {

                              

                               try {

                                      cm = (ChatMessage) sInput.readObject();

                               }

                               catch (IOException e) {

                                      display(username + " Exception reading Streams: " + e);

                                      break;                        

                               }

                               catch(ClassNotFoundException e2) {

                                      break;

                               }

                      

                               String message = cm.getMessage();

                               switch(cm.getType()) {

                               case ChatMessage.MESSAGE:

                                      broadcast(username + ": " + message);

                                      break;

                               case ChatMessage.LOGOUT:

                                      display(username + " disconnected with a LOGOUT message.");

                                      keepGoing = false;

                                      break;

                               case ChatMessage.WHOISIN:

                                      writeMsg("List of the users connected at " + sdf.format(new Date()) + " ");

                                                                            for(int i = 0; i < al.size(); ++i) {

                                              ClientThread ct = al.get(i);

                                              writeMsg((i+1) + ") " + ct.username + " since " + ct.date);

                                      }

                                      break;

                               }

                       }

                      

                       remove(id);

                       close();

               }

              

               private void close() {

                                              try {

                               if(sOutput != null) sOutput.close();

                       }

                       catch(Exception e) {}

                       try {

                               if(sInput != null) sInput.close();

                       }

                       catch(Exception e) {};

                       try {

                               if(socket != null) socket.close();

                       }

                       catch (Exception e) {}

               }

               private boolean writeMsg(String msg) {                      

                       if(!socket.isConnected()) {

                               close();

                               return false;

                       }

                      

                       try {

                               sOutput.writeObject(msg);

                       }

                      

                       catch(IOException e) {

                               display("Error sending message to " + username);

                               display(e.toString());

                       }

                       return true;

               }

        }

}

import java.net.*;

import java.io.*;

import java.util.*;

public class Client {

       

        private ObjectInputStream sInput;                                   private ObjectOutputStream sOutput;                                           private Socket socket;

        private ClientGUI cg;

       

       

        private String server, username;

        private int port;

       

        Client(String server, int port, String username) {

                              this(server, port, username, null);

        }

        Client(String server, int port, String username, ClientGUI cg) {

               this.server = server;

               this.port = port;

               this.username = username;

                              this.cg = cg;

        }

       

        public boolean start() {

              

                       socket = new Socket(server, port);

               }

              

               catch(Exception ec) {

                       display("Error connectiong to server:" + ec);

                       return false;

               }

              

               String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();

               display(msg);

       

               try

               {

                       sInput = new ObjectInputStream(socket.getInputStream());

                       sOutput = new ObjectOutputStream(socket.getOutputStream());

               }

               catch (IOException eIO) {

                       display("Exception creating new Input/output Streams: " + eIO);

                       return false;

               }

new ListenFromServer().start();

              

               try

               {

                       sOutput.writeObject(username);

               }

               catch (IOException eIO) {

                       display("Exception doing login : " + eIO);

                       disconnect();

                       return false;

               }

              

               return true;

        }

        private void display(String msg) {

               if(cg == null)

                       System.out.println(msg);     

               else

                       cg.append(msg + " ");        

        }

       

       

        void sendMessage(ChatMessage msg) {

               try {

                       sOutput.writeObject(msg);

               }

               catch(IOException e) {

                       display("Exception writing to server: " + e);

               }

        }

        private void disconnect() {

               try {

                       if(sInput != null) sInput.close();

               }

               catch(Exception e) {}

               try {

                       if(sOutput != null) sOutput.close();

               }

               catch(Exception e) {}

        try{

                       if(socket != null) socket.close();

               }

               catch(Exception e) {}

              

               if(cg != null)

                       cg.connectionFailed();

                      

        }

       

        public static void main(String[] args) {

              

               int portNumber = 1500;

               String serverAddress = "localhost";

               String userName = "Anonymous";

               switch(args.length) {

                      

case 3:

                               serverAddress = args[2];

                                              case 2:

                               try {

                                      portNumber = Integer.parseInt(args[1]);

                               }

                               catch(Exception e) {

                                      System.out.println("Invalid port number.");

                                      System.out.println("Usage is: > java Client [username] [portNumber] [serverAddress]");

                                      return;

                               }

                       case 1:

                               userName = args[0];

                                              case 0:

                               break;

                      

                       default:

                               System.out.println("Usage is: > java Client [username] [portNumber] {serverAddress]");

                       return;

               }

                              Client client = new Client(serverAddress, portNumber, userName);

              

               if(!client.start())

                       return;

              

               Scanner scan = new Scanner(System.in);

              

               while(true) {

                       System.out.print("> ");

                      

                       String msg = scan.nextLine();

                      

                       if(msg.equalsIgnoreCase("LOGOUT")) {

                               client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));

                              

                               break;

                       }

                      

("WHOISIN")) {

                               client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));                       

                       }

                       else {                        

                               client.sendMessage(newChatMessage(ChatMessage.MESSAGE, msg));

                       }

               }

              

               client.disconnect();  

        }

        class ListenFromServer extends Thread {

               public void run() {

                       while(true) {

                               try {

                                      String msg = (String) sInput.readObject();

                                                                            if(cg == null) {

                                              System.out.println(msg);

                                              System.out.print("> ");

                                      }

                                      else {

                                              cg.append(msg);

                                      }}

                               catch(IOException e) {

                                      display("Server has close the connection: " + e);

                                      if(cg != null)

                                              cg.connectionFailed();

                                      break;

                               }

                                                              catch(ClassNotFoundException e2) {

                               }}}}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote