Microsoft Word - netp2.doc 1 PROJECT 2, A Simple Chat Service Due Date: Oct. 21, XXXXXXXXXXpoints) In this project you will develop a simple multi-threaded chat service. The client and server programs...

1 answer below »
i just need the code



Microsoft Word - netp2.doc 1 PROJECT 2, A Simple Chat Service Due Date: Oct. 21, 2021 (100 points) In this project you will develop a simple multi-threaded chat service. The client and server programs will run from the command line with the same command line arguments as in project 1. The functionality of the server and client are outlined below. The server program is multi-threaded so that it can accept multiple simultaneous connections. The server program logs and broadcasts every chat message it receives from any client. For each connection, the server creates a new thread and hands the connection to it. The server then waits for the next connection. The server program creates a chat file called ‘xy_chat.txt’ upon the establishment of the first connection (the first client connects to the server) and it stores the chat messages inside this file. The chat messages from all the subsequent connections (clients) are stored in the same file as long as there is at least one connection still open. The server deletes the chat file when the last connection is closed (i.e., the last client disconnects and leaves the chat room). The server will create a new chat file each time a client joins an empty chat room. Since every thread that manages the communications with a client can read from and write to the chat file, the activities of these threads must be coordinated (synchronized), otherwise things might go wrong. A thread must have an exclusive access (or a lock) to the chat file before writing to it. When a connection is made (a client connects to the server), the thread that manages the connection waits for a username, and then it sends the content of the chat file to the client. It also logs the arrival of the new client into the chat file and broadcasts the arrival message to each of the other clients connected to the server (i.e., it is broadcasted to the chat room). Any message sent from the client after this point, except DONE, is logged into the chat file and is broadcasted to each of the other clients connected to the server. For DONE, the thread logs and broadcasts the departure of the client from the chat room. When the client signals that it is ready to leave the chat session (sending DONE), the thread will close the client connection, and then will terminate. As mentioned above, the server logs and broadcasts every chat message it receives from any client. If the server gets a chat message from client A, then client A must be excluded from the list of clients that will get the message (the server shouldn’t echo the message back to the same client). The client program establishes a connection to the server, sends the username over, and then prepares to receive the content of the chat file. Now, the client is ready to participate in the ongoing chat. The client program must have two threads in order to implement a full duplex communication (i.e., send and receive simultaneously). One thread sends whatever the user types at the keyboard to the server, and the other 2 thread (say the main thread) displays whatever it receives from the server. The user can leave the chat room at any time by typing ‘DONE’ at the keyboard, and the client program will send that message to the server. The client program then prepares to receive the final report which includes the number of messages received by the server and the length of the session in the form of “hours::minutes::seconds::milliseconds”. The client program then terminates gracefully. Test the program thoroughly, and make sure it works smoothly when multiple users join the chat room and start simultaneous chat. There is no limit on the size of the chat room and it can grow and shrink dynamically. Prior to submitting your project to the class website, upload your server program to your VM on the GCP, start the server on the background, and test it to make sure it works. When you are done with testing your program, kill the server process and stop your VM. Otherwise, you will be charged daily for those resources. Submission requirements: Please submit the following material to the class website for grading on the due date. - copy all of your files (xyz_TCPServer.java xyz_TCPClient.java xyz_Readme.txt, etc.) into a folder named xyz_proj2 and compress that folder. - submit the zip file (xyz_proj2.zip) to the class website on ‘canvas.emich.edu’ Note “xyz” represents your first, last, and middle initials. Microsoft Word - Project2 Rubric.docx RubricforProject#2(100pointstotal) Readmefile(10points) -Nameandprojectdescription(0-4points) -Howtocompileandrunwithexamples(0-3points) -Conclusion(approximatetime,problemsencountered,etc,0-3points) Projectdocumentation(10points) -Nameandprojectdescription(0-3points) -ClassandMethoddescriptions(0-4points) -in-linedocumentation(0-3points) Projectandfilesarenamedasspecified(4points) -Projectisnamedxy_proj1(0-2points) -Filesinsidetheprojectarenamedasspecified(0-2points) Command-lineoptions(8points) -Servercommand-lineoption(0-2points) -Clientcommand-lineoptions(0-6points) -Nohardcodedarguments(0-2points) -promptsfortheusernameifitisnotgiven(0-2points) -handlesallcasescorrectly(0-2points) Chatfileimplementationandusage(15points) -Chatfileiscreatedbeforethefirstclientjoinsthechatroom(5points) -Chatfileisdeletedafterthelastclientleavesthechatroom(5points) -Canviewcontentsofthechatfilewhenchatroomisnotempty(5points) Serverprogram(28) -Serversendsthecontentsofthechatfiletoanewclient(4points) -Serverlogsarrivalanddeparturemessagestothechatfile(3points) -Serverbroadcastsarrivalanddeparturemessages(3points) -Serverlogsmessagescorrectlytothechatfile(4points) -Broadcastmessagesaresenttoalltheclientsexcepttheclientwhosent themessage(4points) -Shareddatastructuresareupdatedinsidesynchronizedblocks(5points) -ServerrunsonGCPcorrectly(5points) Clientprogram(14points) -Clientismultithreaded(5points) -Clientdisplayschatmessagescorrectlyandneatly(4points) -Clientreturnstocommandpromptautomaticallywhenitisfinished(2points) -Clientdisplaysthenumberofmessagesandthesessiontime(3points) Connectiontime(8points) -Measuredandcomputedcorrectly(0-4points) -Formattedcorrectly(hours::minutes::seconds::milliseconds,0-4points) Client/Severprogramsdon’tdisplayanerrormessageforbadoptions(3points) ntankasa project1/NTANKASA_Project 1.zip NTANKASA_Project 1/nta_proj1/nta_TCPClient.java NTANKASA_Project 1/nta_proj1/nta_TCPClient.java // Programmer: COSC 439/522, F '21 // Client program // File name: TCPClient.java // When you run this program, you must give both the host name and // the service port number as command line arguments. For example, // java TCPClient localhost 22222 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class nta_TCPClient {     private static final String PORT_IDENTIFIER = "-p";     private static final String HOST_IDENTIFIER = "-h";     private static final String USER_NAME_IDENTIFIER = "-u";     private static final int DEFAULT_SERVER_PORT = 21400;     private static int serverPort = DEFAULT_SERVER_PORT;     private static InetAddress serverHost;     private static String userName;     public static void main(String[] args) {         try {             parseArguments(args);             while (!isValidUserName()) {                 System.out.println("Please enter a UserName : ");                 Scanner scanner = new Scanner(System.in);                 userName = scanner.next();             }         } catch (UnknownHostException e) {             System.out.println("Host ID not found!");             System.exit(1);         } catch (Exception e) {             System.out.println("Exception occurred while running the program " + e.getMessage());             System.exit(1);         }         run(serverPort);     }     /**      * Method to check if the user name is valid      *      * @return boolean true if username is valid, false otherwise      */     private static boolean isValidUserName() {         return userName != null && !userName.isEmpty();     }     /**      * Method to parse the command line arguments, initialize argument variable with default if not passed      *      * @param args : command line arguments      * @throws UnknownHostException : exception indicating invalid host address      */     private static void parseArguments(String[] args) throws UnknownHostException {         serverPort = DEFAULT_SERVER_PORT;         serverHost = InetAddress.getLocalHost();         for (int argIndex = 0; argIndex < args.length; argindex += 2) {             switch (args[argindex]) {=""                 case user_name_identifier:=""                     username =" args[argIndex + 1];"                     break;=""                 case port_identifier:=""                     serverport =" Integer.parseInt(args[argIndex + 1]);"                     break;=""                 case host_identifier:=""                     serverhost =" InetAddress.getByName(args[argIndex + 1]);"                     break;=""                 default:=""                     system.out.println("invalid command line param " + args[argindex]);=""             }=""         }=""     }=""     private static void run(int port) {=""         socket link =" null;"         try {=""             // establish a connection to the server=""             link =" new Socket(serverHost, port);"             // set up input and output streams for the connection=""             bufferedreader in =" new BufferedReader("                     new inputstreamreader(link.getinputstream()));=""             printwriter out =" new PrintWriter("                     link.getoutputstream(), true);=""             //send username to the server=""             out.println(username);=""             //set up stream for keyboard entry=""             bufferedreader userentry =" new BufferedReader(new InputStreamReader(System.in));"             string message, response;=""             // get data from the user and send it to the server=""             do {=""                 system.out.print("enter message: ");=""                 message =" userEntry.readLine();"                 out.println(message);=""             } while (!message.equals("done"));=""             // receive and print the final report from the server and close the connection=""             while ((response =" in.readLine()) != null) {"                 system.out.println(response);=""             }=""         } catch (ioexception e) {=""             e.printstacktrace();=""         } finally {=""             try {=""                 system.out.println("\n!!!!! closing connection... !!!!!");=""                 link.close();=""             } catch (ioexception e) {=""                 system.out.println("unable to disconnect!");=""                 system.exit(1);=""             }=""         }=""     }="" }="" ntankasa_project="" 1/nta_proj1/nta_tcpserver.java="" ntankasa_project="" 1/nta_proj1/nta_tcpserver.java=""  programmer: cosc 439/522, f '21=""  server program=""  file name: "tcpserver.java"=""  when you run this program, you must give the service port=""  number as a command line argument. for example,=""  java tcpserver 22222="" import java.io.*;="" import java.net.inetaddress;="" import java.net.serversocket;="" import java.net.socket;="" import java.nio.file.files;="" import java.nio.file.path;="" public class nta_tcpserver {=""     private static final int default_port =" 21400;"     private static final string port_identifier =" "-p";"     private static final string file_name =" "nta_chat";"     private static final string file_extension =" "txt";"     private static serversocket servsock;=""     private static int port =" DEFAULT_PORT;"     private static path chatfilepath;=""     public static void main(string[] args) {=""         system.out.println("opening port...\n");=""         try {=""             // create a server object=""             parsearguments(args);=""             servsock =" new ServerSocket(port);"         } catch (ioexception e) {=""             system.out.println("unable to attach to port!");=""             system.exit(1);=""         }=""         do {=""             run();=""         } while (true);=""     }=""     private static void parsearguments(string[] args) {=""         port =" DEFAULT_PORT;"         for (int argindex ="">< args.length; argindex += 2) {             if (port_identifier.equals(args[argindex])) {                 port = integer.parseint(args[argindex + 1]);             } else {                 system.out.println("invalid command line param " + args[argindex]);             }         }     }     //hours::minutes::seconds::milliseconds     private static string format(long timeinmillis) {         long giventime = timeinmillis;         long secondsinmilli = 1000;         long minutesinmilli = secondsinmilli * 60;         long hoursinmilli = minutesinmilli * 60;         long elapsedhours = giventime / hoursinmilli;         giventime = giventime % hoursinmilli;         long elapsedminutes = giventime / minutesinmilli;         giventime = giventime % minutesinmilli;         long elapsedseconds = giventime / secondsinmilli;         long elapsedmilliseconds = giventime % secondsinmilli;         return string.format("%02d::%02d::%02d::%03d",                 elapsedhours, elapsedminutes, elapsedseconds, elapsedmilliseconds);     }     private static void run() {         socket link = null;         try {             // put the server into a waiting state             link = servsock.accept();             long starttime = system.currenttimemillis();             // set up input and output streams for socket             bufferedreader in = new bufferedreader(new inputstreamreader(link.getinputstream()));             printwriter out = new printwriter(link.getoutputstream(), true);             // print local host name             string host = inetaddress.getlocalhost().gethostname();             system.out.println("client has established a connection to " + host);             //create chat file             chatfilepath = files.createtempfile(file_name, file_extension);             bufferedwriter chatfilewriter = files.newbufferedwriter(chatfilepath);             // receive and process the incoming data             int nummessages = 0;             string username = in.readline();             string message = in.readline();             while (!message.equals("done")) {                 system.out.println(message);                 //write the messages from the user to the chat file                 chatfilewriter.write(username + ":" + message);                 chatfilewriter.write("\n");                 chatfilewriter.flush();                 nummessages++;                 message = in.readline();             }             //close the chat file connection             chatfilewriter.close();             // send a report back and close the connection             out.println(string.format("server received %s messages", nummessages));             files.lines(chatfilepath).foreach(out::println);             //calculate elapsed time and send formatted time to client             long elapsedtime = system.currenttimemillis() - starttime;             out.println("length of session (hours::minutes::seconds::milliseconds) - " + format(elapsedtime));         } catch (ioexception e) {             e.printstacktrace();         } finally {             try {                 system.out.println("!!!!! closing connection... !!!!!\n" + "!!! waiting for the next connection... !!!");                 link.close();                 //destroy chat file                 files.delete(chatfilepath);                 system.out.println("!!! chat file deleted !!!");             } catch (ioexception e) {                 system.out.println("unable to disconnect!");                 system.exit(1);             }         }     } }             if (port_identifier.equals(args[argindex])) {=""                 port =" Integer.parseInt(args[argIndex + 1]);"             } else {=""                 system.out.println("invalid command line param " + args[argindex]);=""             }=""         }=""     }=""     //hours::minutes::seconds::milliseconds=""     private static string format(long timeinmillis) {=""         long giventime =" timeInMillis;"         long secondsinmilli =" 1000;"         long minutesinmilli =" secondsInMilli * 60;"         long hoursinmilli =" minutesInMilli * 60;"         long elapsedhours =" givenTime / hoursInMilli;"         giventime =" givenTime % hoursInMilli;"         long elapsedminutes =" givenTime / minutesInMilli;"         giventime =" givenTime % minutesInMilli;"         long elapsedseconds =" givenTime / secondsInMilli;"         long elapsedmilliseconds =" givenTime % secondsInMilli;"         return string.format("%02d::%02d::%02d::%03d",=""                 elapsedhours, elapsedminutes, elapsedseconds, elapsedmilliseconds);=""     }=""     private static void run() {=""         socket link =" null;"         try {=""             // put the server into a waiting state=""             link =" servSock.accept();"             long starttime =" System.currentTimeMillis();"             // set up input and output streams for socket=""             bufferedreader in =" new BufferedReader(new InputStreamReader(link.getInputStream()));"             printwriter out =" new PrintWriter(link.getOutputStream(), true);"             // print local host name=""             string host =" InetAddress.getLocalHost().getHostName();"             system.out.println("client has established a connection to " + host);=""             //create chat file=""             chatfilepath =" Files.createTempFile(FILE_NAME, FILE_EXTENSION);"             bufferedwriter chatfilewriter =" Files.newBufferedWriter(chatFilePath);"             // receive and process the incoming data=""             int nummessages =" 0;"             string username =" in.readLine();"             string message =" in.readLine();"             while (!message.equals("done")) {=""                 system.out.println(message);=""                 //write the messages from the user to the chat file=""                 chatfilewriter.write(username + ":" + message);=""                 chatfilewriter.write("\n");=""                 chatfilewriter.flush();=""                 nummessages++;=""                 message =" in.readLine();"             }=""             //close the chat file connection=""             chatfilewriter.close();=""             // send a report back and close the connection=""             out.println(string.format("server received %s messages", nummessages));=""             files.lines(chatfilepath).foreach(out::println);=""             //calculate elapsed time and send formatted time to client=""             long elapsedtime =" System.currentTimeMillis() - startTime;"             out.println("length of session (hours::minutes::seconds::milliseconds) - " + format(elapsedtime));=""         } catch (ioexception e) {=""             e.printstacktrace();=""         } finally {=""             try {=""                 system.out.println("!!!!! closing connection... !!!!!\n" + "!!! waiting for the next connection... !!!");=""                 link.close();=""                 //destroy chat file=""                 files.delete(chatfilepath);=""                 system.out.println("!!! chat file deleted !!!");=""             } catch (ioexception e) {=""                 system.out.println("unable to disconnect!");=""                 system.exit(1);=""             }=""         }=""     }="">
Answered 3 days AfterOct 18, 2021

Answer To: Microsoft Word - netp2.doc 1 PROJECT 2, A Simple Chat Service Due Date: Oct. 21, XXXXXXXXXXpoints)...

Swapnil answered on Oct 21 2021
130 Votes
94063/Chat File Implementation/Chat File Implementation.txt
To implement the caht file and its usage you need to run the project files server.java file and client.java file.
1) Chat file is created before the first client joins the chat room.
The chat file consist of components for the first client that can joins the chat room and these are:
- A header which can basicaly shows the user name and the current room along with set of clients in the room.
- Main body that can have the messages came thorugh communication.
- Footer which can be consisted to the client type messege.

2) Chat file is deleted after the last client    leaves the chat room.
The caht file can be deleted after having the client leaves into the chat room and that can handle the mesages in the event emitter to whenever user sends the messages.
It can emits the again and again in the entire room.
3) Can view contents of the chat file when chat room is not empty.
The view content of the chat file clears the event emitter which can be triggered to the sending the messages. That can be picked by the username and the room which can be redirects to the user.
94063/Client Program/nta_TCPClient.class
94063/Client Program/nta_TCPClient.java
94063/Client Program/nta_TCPClient.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class nta_TCPClient 
{
    private static InetAddress host;
    private static String hostAddress = "localhost";
    private static String portNumber = "21400";
    private static String username = "";
    public static void main(String[] args) 
    {
        for(int argIndex = 0; argIndex < args.length; argIndex += 2) 
        {
            switch (args[argIndex]) 
            {
                case "-u":
                    username = args[argIndex + 1];
                    break;
                case "-h":
                    hostAddress = args[argIndex + 1];
                    break;
                case "-p":
                    portNumber = args[argIndex + 1];
                    break;
                default:
                    System.out.println("Invalid Commnad Line Arguments...");
                    System.exit(1);
            }
        }
        if(username.isEmpty()) 
        {
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Please enter a username: ");
            username = keyboard.nextLine();
        }
        try 
        {
            host = InetAddress.getByName(hostAddress);
        } 
        catch (UnknownHostException e) 
        {
            System.out.println("Host ID not found!");
            System.exit(1);
        }
        run(Integer.parseInt(portNumber));
    }
    private static void run(int port) 
    {
        Socket link = null;
        try 
        {
            link = new Socket(host, port);
            BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));
            PrintWriter out = new PrintWriter(link.getOutputStream(), true);
            BufferedReader userEntry = new BufferedReader(new InputStreamReader(System.in));
            String message, response;
            out.println(username);
            do 
            {
                System.out.print("Enter message: ");
                message = userEntry.readLine();
                out.println(message);
            } 
            while (!message.equals("DONE"));
            response = in.readLine();
            while(!response.equals("DONE")) 
            {
                System.out.println(response);
                response = in.readLine();
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        finally 
        {
            try 
            {
                System.out.println("\n!!!!! Closing connection... !!!!!");
                link.close();
            } 
            catch (IOException e) 
            {
                System.out.println("Unable to disconnect!");
                System.exit(1);
            }
        }
    }
}
94063/Command line Options/Command Line Options.txt
To run the project file you can use the commnad prompt.
1.Compile programs using following commands.
2.To run Sever, type in javac Server.java /java Server
3.For the Client part, type in javac Client.java /java Client
94063/Connection Time/userThread.class
94063/Project Documentation/Project Documentation.docx
Title: A Simple Chat Service
Description:
1. Server: The main server implementation is easy and easy to understand. The following points will help understand Server implementation:
- The server runs an infinite loop to keep accepting incoming requests.
- When a request comes, it assigns a new thread to handle the communication part.
- The server also stores the client name to keep a track of connected devices.
2. Client: The following points will help understand Client implementation:
- Whenever the handler receives any string, it breaks it into the message and recipient part.
- It uses String tokenizer for this purpose with the delimiter.
- It then searches for the name of recipient in the connected clients list, stored as in the server.
- If it finds the recipient’s name in the clients list then it forwards the message on its output stream with the name of the sender prefixed to the message.
Compilation:
1.Compile programs using following commands.
2.To run Sever, type in javac Server.java /java Server
3.For the Client part, type in javac Client.java /java Client
Conclusion:
An implementation of server manages to handle the most of the scenarios. If the number of clients grew large then the searching time would increase in the handler class. The server program is multi-threaded so that it can accept multiple simultaneous...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here