Java program – Online Address Book (server client application)

Java program – Online Address Book (server client application)

package com.mycompany.onlineaddressbook;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

Don't use plagiarized sources. Get Your Custom Essay on
Java program – Online Address Book (server client application)
Just from $13/Page
Order Essay

//Runnable class allows us to create a task
//to be run on a thread
public class ClientHandler implements Runnable {
private Socket socket; //connected socket
private ServerSocket serverSocket; //server’s socket
private int clientNumber;

//create an instance
public ClientHandler(int clientNumber, Socket socket, ServerSocket serverSocket) {
this.socket = socket;
this.serverSocket = serverSocket;
this.clientNumber = clientNumber;
}//end ctor

//run() method is required by all
//Runnable implementers
@Override
public void run() {
//run the thread in here
try {
DataInputStream inputFromClient =
new DataInputStream(socket.getInputStream());

DataOutputStream outputToClient =
new DataOutputStream(socket.getOutputStream());

//continuously serve the client
while(true) {
String strReceived = inputFromClient.readUTF();
System.out.println(“\n\t[[Command ” + strReceived +
” received from client ” + clientNumber +”]]”);

if(strReceived.equalsIgnoreCase(“add”)) {
System.out.println(“adding handlet client ” +
clientNumber);
outputToClient.writeUTF(“handler was added ” +
clientNumber + “!”);
}
else if(strReceived.equalsIgnoreCase(“quit”)) {
System.out.println(“Shutting down server…”);
outputToClient.writeUTF(“Shutting down server…”);
serverSocket.close();
socket.close();
break; //get out of loop
}
else {
System.out.println(“Unknown command received: ”
+ strReceived);
outputToClient.writeUTF(“Unknown command. ”
+ “Please try again.”);

}
}//end while
}
catch(IOException ex) {
ex.printStackTrace();
}//end try-catch

}//end run

}//end ClientHandler

package com.mycompany.onlineaddressbook;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class MultiServerJPB1 {

private static final int SERVER_PORT = 8765;

public static void main(String[] args) {
//createCommunicationLoop();
createMultithreadCommunicationLoop();
}//end main

public static void createMultithreadCommunicationLoop() {
int clientNumber = 0;

try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
System.out.println(“Server started on ” + new Date() + “.”);
//listen for new connection request
while(true) {
Socket socket = serverSocket.accept();
clientNumber++; //increment client num

//Find client’s host name
//and IP address
InetAddress inetAddress = socket.getInetAddress();
System.out.println(“Connection from client ” +
clientNumber);
System.out.println(“\tHost name: ” +
inetAddress.getHostName());
System.out.println(“\tHost IP address: “+
inetAddress.getHostAddress());

//create and start new thread for the connection
Thread clientThread = new Thread(
new ClientHandler(clientNumber, socket, serverSocket));
clientThread.start();
}//end while
}
catch(IOException ex) {
ex.printStackTrace();
}

}//end createMultithreadCommunicationLoop

public static void createCommunicationLoop() {
try {
//create server socket
ServerSocket serverSocket =
new ServerSocket(SERVER_PORT);

System.out.println(“Server started at ” +
new Date() + “\n”);
//listen for a connection
//using a regular *client* socket
Socket socket = serverSocket.accept();

//now, prepare to send and receive data
//on output streams
DataInputStream inputFromClient =
new DataInputStream(socket.getInputStream());

DataOutputStream outputToClient =
new DataOutputStream(socket.getOutputStream());

//server loop listening for the client
//and responding
while(true) {
String strReceived = inputFromClient.readUTF();

if(strReceived.equalsIgnoreCase(“add”)) {
System.out.println(“addin client”);
outputToClient.writeUTF(“client was added!”);
}
else if(strReceived.equalsIgnoreCase(“quit”)) {
System.out.println(“Shutting down server…”);
outputToClient.writeUTF(“Shutting down server…”);
serverSocket.close();
socket.close();
break; //get out of loop
}
else {
System.out.println(“Unknown command received: ”
+ strReceived);
outputToClient.writeUTF(“Unknown command. ”
+ “Please try again.”);

}
}//end server loop
}
catch(IOException ex) {
ex.printStackTrace();
}//end try-catch
}//end createCommunicationLoop
}

Online Address Book II

1

. The Assignment 2

For this assignment, the server must allow multiple clients connect the server at the same time. You are required to implement a multithreaded server (such as Pthread or Java thread) and a client that can monitor the server’s message and the user’s input at the same time (e.g. using select() or threads).

Besides the original five commands ADD, DELETE, LIST, SHUDOWN, QUIT, you will need to implement four new commands, LOGIN, LOGOUT, WHO, LOOK, on the client side and the corresponding functions on the server side.

The details of the protocol depend on the command the client sends to the server.

LOGIN

Identify the user to the remote server. A client that wants to login should begin by sending the ASCII string “LOGIN” followed by a space, followed by a UserID, followed by a space, followed by a Password, and followed by the newline character (i.e., ‘\n’).

Your server should be initialized with the UserIDs and Passwords of at least four users who will be allowed to execute the ADD, DELETE, and SHUTDOWN (the root user only) commands at the server. However, a user is allowed to execute the LIST, WHO, LOOK, and QUIT commands anonymously (without login).

When the server receives a LOGIN command from a client, it should check if the UserID and Password are correct and match each other. If they are not correct or don’t match each other, the server should return the string “410 Wrong UserID or Password,” otherwise it should return the “200 OK” message.

A client-server interaction with the LOGIN command thus looks like:

c: LOGIN john john01

s: 200 OK

LOGOUT

Logout from the server. A user is not allowed to send ADD, DELETE, and SHUTDOWN commands after logout, but it can still send LIST, LOOK, WHO, and QUIT commands.

A client-server interaction with the LOGOUT command looks like:

c: LOGOUT

s: 200 OK

WHO

List all active users, including the UserID and the users IP addresses.

A client-server interaction with the WHO command thus looks like:

c: WHO

s: 200 OK

The list of the active users:

john 141.215.10.30

root 127.0.0.1

LOOK

Look up a name in the book. Display the complete name and phone number record. A client sends the ASCII string “LOOK” followed by a space, followed by a number (1 – look for the first name, 2 – look for the last name, 3 – look for the phone number), followed by a name or a phone number, and followed by the newline character (i.e., ‘\n’).

When the server receives an LOOK command from a client, it will look up the name or the phone number in the address book. When there is a match, it returns the “200 OK” message and all the matched record (s). If there is no match, it returns the “404 Your search did not match any records”.

A client-server interaction with the LOOK command thus looks like:

c: LOOK 2 Miller

s: 200 OK

Found 2 match

1001 David Miller 313-510-6001

1004 John Miller 315-123-1345

c: LOOK 3 313-231-1324

s: 404 Your search did not match any records

ADD and DELETE

The basic requirement is the same as the assignment 1 except that a user needs to login first to execute these commands. If a user has not logged in, the server will return a “401 You are not currently logged in, login first” message

LIST

Same as the assignment 1.

SHUTDOWN

The basic requirement is the same as the assignment 1 except that only the “root” user can execute this command. When your server receives a SHUTDOWN command from a client, it should check if the current user is the root. If it is not the root user, the server should return a “402 User not allowed to execute this command” message.

In addition, the SHUTDOWN will make all clients and the server terminate.

A client-server interaction with the SHUTDOWN command thus looks like:

c: SHUTDOWN
s: 200 OK

At the windows of all clients

s: 210 the server is about to shutdown ……

QUIT

If a user logged in from the current client, QUIT also logout the user.

Note, a user can execute WHO, LIST, and QUIT commands before logged in.

2. Format

You should form a team of two students (or work individually) and then jointly design your project. While each project should be an integrated effort, you should identify in your README file what part of the project each member is responsible for.

I assume you will work in the same group as you did for project 1. If there is any change, please let me know.

3. Programming Environment

You can use either C/C++ or Java to implement the assignments. The assignments will be tested on the UMD Login servers (login.umd.umich.edu). For easy grading, please don’t use any GUI interface.

4. Requirements

The following items are required for full-credit:

· implement all nine commands: ADD, DELETE, LIST, QUIT, SHUTDOWN, LOGIN, LOGOUT, WHO, LOOK

· all users share the same address book. The users information should be maintained by the server. You must have the following users (lower case) in your system:

UserID Password

root root01

john john01

david david01

mary mary01

· make sure that you do sufficient error handling such that a user can’t crash your server. For instance, what will you do if a user provides invalid input?

· the client should be able to connect to the server running on any machine. Therefore, the server IP address should be a command line parameter for the client program.

· the server should print out all messages received from clients on the screen.

· when the previous client exits, the server should allow the next client connect.

· your source codes must be commented

· include a README file in your submission.

· include a Makefile in your submission.

Note: in your README file, the following information should be included: the functions that have been implemented, the instructions about how to compile and run your program, known bugs. Also, in either the README or a separate PDF or DOCX, you should have
sample outputs of a complete test of all commands you implemented.

5. Grading (100 points)

· Correctness, Robustness, and Documentation of Working Program (90 points)

· You will lose at least 10 points for any bugs that cause the system crash.

· You will lose at least 5 points for any other bugs.

· You must turn in screen shots in a PDF or DOCX file of that program working – verifying the new functionality

· Comments and style (5 points)

· README (5 points)

1

package com.mycompany.onlineaddressbook;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class ClientJPB1 {

private static final int SERVER_PORT = 8765;
public static void main(String[] args) {

DataOutputStream toServer;
DataInputStream fromServer;
Scanner input =
new Scanner(System.in);
String message;

//attempt to connect to the server
try {
Socket socket =
new Socket(“localhost”, SERVER_PORT);

//create input stream to receive data
//from the server
fromServer = new DataInputStream(socket.getInputStream());

toServer = new DataOutputStream(socket.getOutputStream());

System.out.println(“Online Address Book II\t”);
System.out.println(“———————-\t”);
System.out.println(“List of Commands:\t”);
System.out.println(“Add”+”, Delete”+”, List”+”, Who”+”, Look”+”, Quit”+”, Login”+”, Logout”+”, Shutdown”);
System.out.println(“Send command to server:\t”);
while(true) {

System.out.print(“Send command to server:\t”);
message = input.nextLine();
toServer.writeUTF(message);

if(message.equalsIgnoreCase(“quit”)) {
break;
}

//received message:
message = fromServer.readUTF();
System.out.println(“Server says: ” + message);
}

}
catch(IOException ex) {
ex.printStackTrace();
}//end try-catch

}//end main
}

What Will You Get?

We provide professional writing services to help you score straight A’s by submitting custom written assignments that mirror your guidelines.

Premium Quality

Get result-oriented writing and never worry about grades anymore. We follow the highest quality standards to make sure that you get perfect assignments.

Experienced Writers

Our writers have experience in dealing with papers of every educational level. You can surely rely on the expertise of our qualified professionals.

On-Time Delivery

Your deadline is our threshold for success and we take it very seriously. We make sure you receive your papers before your predefined time.

24/7 Customer Support

Someone from our customer support team is always here to respond to your questions. So, hit us up if you have got any ambiguity or concern.

Complete Confidentiality

Sit back and relax while we help you out with writing your papers. We have an ultimate policy for keeping your personal and order-related details a secret.

Authentic Sources

We assure you that your document will be thoroughly checked for plagiarism and grammatical errors as we use highly authentic and licit sources.

Moneyback Guarantee

Still reluctant about placing an order? Our 100% Moneyback Guarantee backs you up on rare occasions where you aren’t satisfied with the writing.

Order Tracking

You don’t have to wait for an update for hours; you can track the progress of your order any time you want. We share the status after each step.

image

Areas of Expertise

Although you can leverage our expertise for any writing task, we have a knack for creating flawless papers for the following document types.

Areas of Expertise

Although you can leverage our expertise for any writing task, we have a knack for creating flawless papers for the following document types.

image

Trusted Partner of 9650+ Students for Writing

From brainstorming your paper's outline to perfecting its grammar, we perform every step carefully to make your paper worthy of A grade.

Preferred Writer

Hire your preferred writer anytime. Simply specify if you want your preferred expert to write your paper and we’ll make that happen.

Grammar Check Report

Get an elaborate and authentic grammar check report with your work to have the grammar goodness sealed in your document.

One Page Summary

You can purchase this feature if you want our writers to sum up your paper in the form of a concise and well-articulated summary.

Plagiarism Report

You don’t have to worry about plagiarism anymore. Get a plagiarism report to certify the uniqueness of your work.

Free Features $66FREE

  • Most Qualified Writer $10FREE
  • Plagiarism Scan Report $10FREE
  • Unlimited Revisions $08FREE
  • Paper Formatting $05FREE
  • Cover Page $05FREE
  • Referencing & Bibliography $10FREE
  • Dedicated User Area $08FREE
  • 24/7 Order Tracking $05FREE
  • Periodic Email Alerts $05FREE
image

Our Services

Join us for the best experience while seeking writing assistance in your college life. A good grade is all you need to boost up your academic excellence and we are all about it.

  • On-time Delivery
  • 24/7 Order Tracking
  • Access to Authentic Sources
Academic Writing

We create perfect papers according to the guidelines.

Professional Editing

We seamlessly edit out errors from your papers.

Thorough Proofreading

We thoroughly read your final draft to identify errors.

image

Delegate Your Challenging Writing Tasks to Experienced Professionals

Work with ultimate peace of mind because we ensure that your academic work is our responsibility and your grades are a top concern for us!

Check Out Our Sample Work

Dedication. Quality. Commitment. Punctuality

Categories
All samples
Essay (any type)
Essay (any type)
The Value of a Nursing Degree
Undergrad. (yrs 3-4)
Nursing
2
View this sample

It May Not Be Much, but It’s Honest Work!

Here is what we have achieved so far. These numbers are evidence that we go the extra mile to make your college journey successful.

0+

Happy Clients

0+

Words Written This Week

0+

Ongoing Orders

0%

Customer Satisfaction Rate
image

Process as Fine as Brewed Coffee

We have the most intuitive and minimalistic process so that you can easily place an order. Just follow a few steps to unlock success.

See How We Helped 9000+ Students Achieve Success

image

We Analyze Your Problem and Offer Customized Writing

We understand your guidelines first before delivering any writing service. You can discuss your writing needs and we will have them evaluated by our dedicated team.

  • Clear elicitation of your requirements.
  • Customized writing as per your needs.

We Mirror Your Guidelines to Deliver Quality Services

We write your papers in a standardized way. We complete your work in such a way that it turns out to be a perfect description of your guidelines.

  • Proactive analysis of your writing.
  • Active communication to understand requirements.
image
image

We Handle Your Writing Tasks to Ensure Excellent Grades

We promise you excellent grades and academic excellence that you always longed for. Our writers stay in touch with you via email.

  • Thorough research and analysis for every order.
  • Deliverance of reliable writing service to improve your grades.
Place an Order Start Chat Now
image

Order your essay today and save 30% with the discount code Happy