I have to create multiple client threads and each one has to login .and i have implemented user_login function as synchronized but when i am calling it in run method of thread ,multiple threads are accessing it same time.I want that only one client should do login first then second and so on...
import java.io.*;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
class Login {
private String username = ""; //username of server manager
private String password = ""; //password of server manager
private String record = "";
private boolean flag = false;
public synchronized String user_login() {
Logger logger; //Reference to Logger class is generated
Handler fileHandler;
SimpleFormatter plainText;
Scanner s;
int thread_name = 0;
try {//login details fetched from login.txt file
BufferedReader br = new BufferedReader(new FileReader("D:/JAVA/assignment1/Login.txt"));
s = new Scanner(System.in);
System.out.println("Enter your username: ");
username = s.nextLine();
System.out.println("Enter your password: ");
password = s.nextLine();
Scanner scan;
while ((record = br.readLine()) != null) { //records fetched line by line
String[] split = record.split(" ");
if (username.equals(split[0]) && password.equals(split[1])) //username and password compared with data fetched
{
System.out.println(" LOGIN SUCCESSFULL for" + thread_name);
flag = true;
logger = Logger.getLogger(Logger.class.getName());
logger.setUseParentHandlers(false);
File f = new File("D:/JAVA/assignment1/" + username + ".txt");
if (!f.exists())
f.createNewFile();
fileHandler = new FileHandler("D:/JAVA/assignment1/" + username + ".txt", true);//File for writting log is opened in append mode
plainText = new SimpleFormatter();
fileHandler.setFormatter(plainText);
logger.addHandler(fileHandler);
logger.info("User " + username + "logged in");
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (flag == false) {
System.out.println("LOGIN UNSUCCESSFULL!!!! ");
System.out.println("Try again: ");
user_login(); //if login fails,user reenter his details
}
return username;
}
}
public class Client_Thread extends Thread {
static String username = ""; //username of server manager
//password of server manager
String record = "";
static String locationname;
static boolean flag = false;
Logger logger; //Reference to Logger class is generated
int thread_name = 0;
Client_Thread(int x) {
thread_name = x;
}
#Override
public void run() //client thread statrs execution
{
System.out.println(this.thread_name);
try {
Login l = new Login();
synchronized(l)
{
username = l.user_login();
}
locationname = username.substring(0, 3);
if (locationname.equals("MTL")) //checks which server's manager logged in
{
Registry reg;
reg = LocateRegistry.getRegistry(2964);
ServerInterface ms = (ServerInterface) reg.lookup("Mtl"); //looks for reference Mtl in registry for montreal server
Operations m = new Operations();
m.Operations1(ms,username); //performs the required function
//logger.info(Logger.class.getName());
} else if (locationname.equals("LVL")) {
Registry reg = LocateRegistry.getRegistry(2965);
ServerInterface ls = (ServerInterface) reg.lookup("Lvl"); //looks for reference Lvl in registry for laval server
Operations m = new Operations();
m.Operations1(ls,username);//performs the required function
} else if (locationname.equals("DDO")) {
Registry reg = LocateRegistry.getRegistry(2966);
ServerInterface ds = (ServerInterface) reg.lookup("Ddo"); //looks for reference Ddo in registry for DDO server
Operations m = new Operations();
m.Operations1(ds,username); //performs the required function
}
} catch (IOException | NotBoundException e1) {
e1.printStackTrace();
}
}
}
public class Client {
static void test_case1()
{
for(int i=0;i<2;i++)
{
Client_Thread c = new Client_Thread(i); //run the new client thread
c.start();
}
}
public static void main(String arg[]) throws RemoteException, NotBoundException {
test_case1();
}
}
output is like this:-
0
1
Enter your username:
Enter your username:
but i should be like:-
Enter your username:
Enter your password:
Each one of your threads creates its own Login object.
Therefore, synchronization has no effect, because each thread synchronizes on a different instance of your Login object.
In order to achieve the desired behavior you have to instantiate only one Login object and pass it to all your threads to use.
Related
I'm confused as to why I cant seem to get the server to output to the client properly. I'm not the most experienced when it comes to java and have exhausted anything I could think of. The other systems in place seem to work fine(The Add/List commands).
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.tcpechoclient;
import java.io.*;
import java.net.*;
/**
*
* #author Leepe
*/
public class TCPEchoClient {
private static InetAddress host;
private static final int PORT = 1248;
public static void main(String[] args) {
try
{
host = InetAddress.getLocalHost();
}
catch(UnknownHostException e)
{
System.out.println("Host ID not found!");
System.exit(1);
}
run();
}
private static void run() {
Socket link = null; //Step 1.
try
{
link = new Socket(host,PORT); //Step 1.
//link = new Socket( "192.168.0.59", PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));//Step 2.
PrintWriter out = new PrintWriter(link.getOutputStream(),true); //Step 2.
//Set up stream for keyboard entry...
BufferedReader userEntry =new BufferedReader(new InputStreamReader(System.in));
String message = "";
String response = "";
while (!message.equals("Stop")) {
System.out.println("Enter message to be sent to server: ");
message = userEntry.readLine();
out.println(message); //Step 3.
// out.flush();
response = in.readLine(); //Step 3.
System.out.println("\nSERVER RESPONSE> " + response);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
System.out.println("\n* Closing connection... *");
link.close(); //Step 4.
}catch(IOException e)
{
System.out.println("Unable to disconnect/close!");
System.exit(1);
}
}
} // finish run method
} //finish the class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.tcpechoserverthreads;
import java.io.*;
import java.net.*;
/**
*
* #author Leepe
*/
public class TCPEchoServer {
private static ServerSocket servSock;
private static final int PORT = 1248;
private static int clientConnections = 0;
public static void main(String[] args) {
System.out.println("Opening port..."+"\n"+"Listening on port: "+PORT);
try
{
servSock = new ServerSocket(PORT); //Step 1.
}
catch(IOException e)
{
System.out.println("Unable to attach to port!");
System.exit(1);
}
do
{
run();
}while (true);
}
synchronized private static void run()
{
Socket link = null; //Step 2.
try
{
link = servSock.accept();
clientConnections++;
String client_ID = clientConnections + "";
Runnable resource = new ClientConnectionRun(link, client_ID);
Thread t = new Thread (resource);
t.start();
}
catch(IOException e1)
{
e1.printStackTrace();
try {
System.out.println("\n* Closing connection... *");
link.close(); //Step 5.
}
catch(IOException e2)
{
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
} // finish run method
} // finish the class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.tcpechoserverthreads;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
/**
*
* #author Leepe
*/
public class ClientConnectionRun implements Runnable {
Socket client_link = null;
String clientID;
public static List<String> currentList = new ArrayList<String>();
String[] parts;
String part1;
String part2;
String part3;
String message = "";
public ClientConnectionRun(Socket connection, String cID) {
this.client_link = connection;
clientID = cID;
}
#Override
synchronized public void run() {
try{
BufferedReader in = new BufferedReader( new InputStreamReader(client_link.getInputStream())); //Step 3.
PrintWriter out = new PrintWriter(client_link.getOutputStream(),true); //Step 3.
System.out.println("\n* started connection with the client " + clientID + " ... *");
while (!message.equals("Stop")){//Step 4.
message = in.readLine();
// out.flush();
System.out.println("\n Message received from client: " + clientID + " - "+ message);
out.println("\n Echo Message: " + message);
//out.flush();
if(message.contains(";")){
// String userinput = message;
// String item = message;
// System.out.println("Contains ;");
String[] parts = message.split(";");
String part1 = parts[0];
String part2 = parts[1];
System.out.println(part1);
System.out.println(part2);
if(parts.length >= 3 && part1.equals("add")){
String part3 = parts[2];
System.out.println(part1);
System.out.println(part2);
System.out.println(part3);
currentList.add(part2+" - "+part3);
//AddItem();
}
else if(parts.length <= 2 && part1.equals("list") ){
System.out.println("list command working");
//ListItem();
System.out.println();
System.out.println("----------------------");
System.out.println("To-Do List");
System.out.println("----------------------");
int number = 0;
for (Iterator<String> it = currentList.iterator(); it.hasNext();) {
message = it.next();
if(message.contains(part2)){
System.out.println(++number + " " + message);
}
}
System.out.println("----------------------");
}
else {
System.out.println("\n Don't add a description if you are searching for a date");
}
}
else if(!message.contains(";")){
System.out.println("\n Unknown command, Try using 'add' or 'list' followed by a ' ; ' as listed above ");
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try {
System.out.println("\n* Closing connection with the client " + clientID + " ... *");
client_link.close(); //Step 5.
}
catch(IOException e)
{
System.out.println("Unable to disconnect!");
}
}
}
}
I want the server to be able to output info to the client that's connected. What's happening is that the server will output the info eventually but requires me to enter several more inputs, i'm not sure how its delayed and any help would be appreciated.
Leaving everything else untouched, simply changing your line out.println("\nEcho Message: " + message); in your Class ClientConnectionRun to out.println("Echo Message: " + message); will fix this.
Essentially, what goes wrong is that your line response = in.readLine(); in the client terminates when it encounters a line-feed. So, if you begin your response with a line-feed, it will terminate instantly and is thus always trailing by one line, which is why you will only see the actual response the next time you enter some input.
From the doc of java.io.BufferedReader.readLine():
Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), a carriage return
followed immediately by a line feed, or by reaching the end-of-file
(EOF).
Also, some general input:
You can drastically improve your code by using try-with-resources statements (since Java 8). This way you can avoid the "nasty" nested try-catch-finally constructs to handle your streams. For your Client for example you could simplify do:
try (Socket 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))) {
And all you need at the end is this:
} catch (IOException e) {
e.printStackTrace();
}
(formatting is off, couldn't post how I copied and pasted from eclipse)
I'm trying to verify the username before moving on to ask for password, I tried splitting username and password out in a service subclass, but that didn't work. Right now, it's going right from username to asking for password even if the username is not stored in the txt file I have it reading form. Here is what I have so far:
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class LoginConsole {
public static User[] loginUsers = new User[4];
private static UserService userService = new UserService();
public static void main (String[] args) throws IOException {
ReadFile();
Scanner input = null;
try {
input = new Scanner(System.in);
boolean validInput = false;
int attempts = 0;
while (!validInput && attempts != 5) {
System.out.println("Enter your username:");
String username = input.nextLine();
System.out.println("Enter your password:");
String password = input.nextLine();
User found = userService.yesFound(username, password);
if (found != null) {
System.out.println("Welcome: " + found.getName());
validInput = true;
break;
} if(attempts < 4) {
System.out.println("Invalid input, please try again!");
attempts++;
} else {
System.out.println("Too many failed attempts, you are
now locked out!");
break;
}
}
} finally {
if (input != null)
input.close();
}
}
private static void ReadFile() throws IOException, FileNotFoundException {
String verInput = "data.txt";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(verInput));
String currLine;
int i = 0;
while ((currLine = reader.readLine()) != null) {
loginUsers[i] = new User(currLine.split(","));
i++;
}
} finally {
if (reader != null)
reader.close();
}
}
}
Since you're trying to verify username before password, then you should validate before you ask for the password.
System.out.println("Enter your username:");
String username = input.nextLine();
// Validate Username here. (example ..)
User user = userService.findUser(username); // you can create a method dedicated to find user.
if(user != null) {
System.out.println("Enter your password:");
String password = input.nextLine();
...
}
I am coding a login program that allows you to set and store a password and username in two separate files (named accordingly). My problem is I can't figure out how to set a username to a password. Ex: Username is Bob, Password is cat, and the user needs to input Bob as the username and cat as the password or else it gives an error(if the user inputs the username as bill and the password as cat, it should detect that the username doesn't go with its respective password). Any help would be nice. *I have not added the username part yet as it is structured the same as the password part, I just need the username to correspond with the password so that the user cannot use a different username with the same password
Here is my code I have so far for a reference:
import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileReader;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class PassCode
{
static String adminPassword = "Change Password";
public static void fileMaker() throws IOException
{
PrintStream standard = System.out;
File f = new File("Password.txt");
FileOutputStream fs= new FileOutputStream(f);
PrintStream ps = new PrintStream(fs);
System.setOut(ps);
String theMessage = "Set New Password";
String userInput = JOptionPane.showInputDialog(theMessage);
System.out.println(userInput);
ps.close();
System.setOut(standard);
}
public static void Checker() throws IOException
{
Scanner inputStream = new Scanner(new FileReader("Password.txt")); //Scans declared file for text on the first line
String fileChecker = inputStream.nextLine(); //Sets scanned line into a string variable
if(fileChecker.isEmpty())
{
fileMaker();
}
else
{
int reply = JOptionPane.showConfirmDialog(null, "Would you like to change the current password", "Warning!", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
String inquire = "Type Administrator Password to Proceed";
boolean flag = true;
while(flag == true)
{
String confirm = JOptionPane.showInputDialog(inquire);
if(confirm.equals(adminPassword))
{
fileMaker();
flag = false;
}
else
{
inquire = "Incorrect!" + "\n" + "Retry";
}
}
}
}
}
public static void main(String[] args) throws IOException
{
Checker();
Scanner inputStreamThree = new Scanner(new FileReader("Password.txt"));
String line = inputStreamThree.nextLine();
String question = "Password Please";
Boolean right = true;
while(right == true)
{
String ask = JOptionPane.showInputDialog(question); //Asks for user to input password
if(ask.equals(adminPassword)) //Checks if user input the admin password
{
fileMaker();
Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
line = adminChecker;
}
else if(line.equals(ask)) //Checks if user password is correct
{
System.out.println("Welcome Fellow Programmer to the Now Functioning Password Checker!" +
"\n" + "Date Today: 10/31/2017" +
"\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
right = false;
}
else if(ask != line) //Checks if user password is incorrect
{
question = "Incorrect Password!";
}
}
}
}
If both username and password are located in the same line number in their respective file, then it should be possible to deduct the right password for a given user.
Example:
Username.txt Password.txt
bob cat
alice rabbit
victor salmon
When searching the username, count the line read until you find the username. Then in the password file, read the number of lines and retrieve the password value. Then compare!
I assume this is academic work because storing password in clear in files is a major security hole and should never be allowed on professional project.
I assume that you use only single login but stored on 2 files Password.txt and Username.txt.
Below is my 10 min codes, so you might need to modified if got typo or error.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class PassCodeA {
public static void main(String[] args)
{
Scanner usernameFile = null;
try {
usernameFile = new Scanner(new FileReader("Username.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Username File Missing", "File Missing", JOptionPane.CLOSED_OPTION);
return;
}
Scanner passwordFile = null;
try {
passwordFile = new Scanner(new FileReader("Password.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Password File Missing", "File Missing", JOptionPane.CLOSED_OPTION);
return;
}
String usernameInput = JOptionPane.showInputDialog(null,"Please Enter Username", "Username", JOptionPane.OK_CANCEL_OPTION);
String passwordInput = JOptionPane.showInputDialog(null,"Please Enter Password", "Username", JOptionPane.OK_CANCEL_OPTION);
System.out.println(usernameInput);
boolean usernameFound = false;
while(usernameFile.hasNextLine()){
final String lineFromFile = usernameFile.nextLine();
if(lineFromFile.equals(usernameInput)){
usernameFound = true;
break;
}
}
if (usernameFound == false) {
JOptionPane.showMessageDialog(null, "Username not found", "Username Not Found", JOptionPane.CLOSED_OPTION);
return;
}
boolean passwordFound = false;
while(passwordFile.hasNextLine()){
final String lineFromFile = passwordFile.nextLine();
if(lineFromFile.equals(passwordInput)){
passwordFound = true;
break;
}
}
if (passwordFound == false) {
JOptionPane.showMessageDialog(null, "Password not found", "Password Not Found", JOptionPane.CLOSED_OPTION);
return;
}
JOptionPane.showMessageDialog(null, "Thank you for login", "Success", JOptionPane.CLOSED_OPTION);
}
}
If you had multiple login credential in that both files. You should use LineNumberReader instead of scanner. So that you can match with line number on both files.
I found a way to implement LineNumberReader(LNR) and have the program check if the line numbers for both the username and password are the same. I used a separate method and called it in the main method. I tested the code and it worked with multiple username info and password info in both files. I know this is messy as well, but I was going for functionality first. Then I will optimize it accordingly. I cannot upload the whole code as it is way to big for space given.
Here is the code I added(just the method with the LNR):
public static void reader() throws IOException
{
JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
"Username:", username,
"Password:", password
};
int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
boolean right = true;
while(right == true)
{
int u = 0;
String userCheck;
FileReader ur = null;
LineNumberReader lnru = null;
try {
ur = new FileReader("username.txt");
lnru = new LineNumberReader(ur);
while ((userCheck = lnru.readLine()) != null)
{
if (userCheck.equals(username.getText()))
{
break;
}
else
{
u = lnru.getLineNumber();
}
}
} catch(Exception e)
{
e.printStackTrace();
} finally {
if(ur!=null)
ur.close();
if(lnru!=null)
lnru.close();
}
int p = 0;
String passCheck;
FileReader pr = null;
LineNumberReader lnrp = null;
try {
pr = new FileReader("Password.txt");
lnrp = new LineNumberReader(pr);
while ((passCheck = lnrp.readLine()) != null)
{
if (passCheck.equals(password.getText()))
{
break;
}
else
{
p = lnrp.getLineNumber();
}
}
} catch(Exception e)
{
e.printStackTrace();
} finally {
if(pr!=null)
pr.close();
if(lnrp!=null)
lnrp.close();
}
if (option == JOptionPane.OK_OPTION)
{
if(password.getText().equals(adminPassword)) //Checks if user input the admin password
{
passMaker();
Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
//lineFromFile = adminChecker;
}
else if(p == u) //Checks if username and password are correct
{
System.out.println("Welcome Fellow Programmer to the Now Functioning login program!" + "\n" + "Date Today: 10/31/2017" + "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
right = false;
}
else //Checks if user password is incorrect
{
option = JOptionPane.showConfirmDialog(null, message, "Login Failed Try Again", JOptionPane.OK_CANCEL_OPTION);
}
}
}
}
I have 3 classes (Client, Server, and Protocol) that allow a user to login and send a message to another user. I'm trying to add a password feature to the program but nothing I've tried has worked so far. I've added my code below, I want to prompt the user to put the password in after the error checking on the username has been done. The password should be compared and checked that it is a match, and only then should the user be able to view their messages and send messages.
Any tips would really be appreciated, thanks!
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String messages = "";
// Makes sure there are only two arguments entered
if(args.length != 2) {
System.err.println("Usage: java Client <host name> <port number>");
System.exit(1);
}
// Stores the command line arguments for readability further in the program
String host = args[0];
int port = Integer.parseInt(args[1]);
try (
// Creates the socket to be used
Socket s = new Socket(host, port);
// Reader and Writer to talk with Server
PrintWriter pw =
new PrintWriter(s.getOutputStream(), true);
BufferedReader bf = new BufferedReader(
new InputStreamReader(s.getInputStream()));
) {
// Reader to read from standard input (keyboard)
BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));
// User interface
while (true) {
System.out.println("Please enter your username: ");
String username = keyboard.readLine();
// Check that the login is valid
if (username == null) {
System.out.println("No username entered");
}
else if (username.contains(" ")) {
System.out.println("Username cannot contain spaces");
}
// Send username to server and return number of messages
else {
pw.println(username);
messages = bf.readLine();
System.out.println("You have " + Integer.parseInt(messages) + " messages");
break;
}
}
// Enable the user to continue reading and composing messages until
// they choose to exit
while (true) {
System.out.println("Would you like to READ, COMPOSE or EXIT?");
String choice = keyboard.readLine();
// Shows the messages left for the user
if (choice.equals("READ")) {
pw.println("READ");
messages = bf.readLine();
if (messages == "0") {
System.out.println("NO MESSAGES");
}
else {
String incoming = bf.readLine();
System.out.println(incoming);
incoming = bf.readLine();
System.out.println(incoming);
}
}
// Allows user to write a message to another user
else if (choice.equals("COMPOSE")) {
pw.println("COMPOSE");
System.out.println("Enter message recipient");
String recipient = keyboard.readLine();
if (recipient == null) {
System.out.println("No recipient username entered");
}
else if (recipient.contains(" ")) {
System.out.println("Recipient username cannot contain spaces");
}
else {
pw.println(recipient);
System.out.println("Enter message to be sent");
String im = keyboard.readLine();
pw.println(im);
System.out.println(bf.readLine());
}
}
else if (choice.equals("EXIT")) {
pw.println("EXIT");
System.exit(1);
}
else {
System.out.println("Error: you must either READ, COMPOSE or EXIT");
}
}
}
// Catches the exception in which the server cannot be found
catch(IOException e) {
System.out.println("Error, could not connect to Server");
System.exit(1);
}
}
}
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
String request;
// Makes sure that the user has specified the correct number of command line arguments
if(args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
try (
// Creates a server socket and waits for a connection
ServerSocket ss = new ServerSocket(port);
// A socket to communicate with the client
Socket cs = ss.accept();
// Reader and Writer to talk with Client
PrintWriter pw =
new PrintWriter(cs.getOutputStream(), true);
BufferedReader bf = new BufferedReader(
new InputStreamReader(cs.getInputStream()));
)
// Links the server to the protocol
{
Protocol protocol = new Protocol();
protocol.storeUsername(bf.readLine());
pw.println(protocol.messagesNumber());
// Loop through user input until EXIT is entered
while (true) {
request = bf.readLine();
// Controls output if user inputs READ
if (request.equals("READ")) {
pw.println(protocol.messagesNumber());
pw.println(protocol.readSender());
pw.println(protocol.readMessage());
}
// Controls input if user inputs COMPOSE
else if (request.equals("COMPOSE")) {
String sender = bf.readLine();
String message = bf.readLine();
if (protocol.append(sender, message)) {
pw.println("MESSAGE SENT");
}
else {
pw.println("MESSAGE FAILED");
}
}
// Exits the server
else {
System.exit(1);
}
}
}
// Catches the exception in which the server cannot find a client
catch(IOException e) {
System.out.println("Failed to find a client");
System.exit(1);
}
}
}
Protocol.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Protocol {
private String username;
private String recipient;
private String sender;
private HashMap<String, ArrayList<String>> senderMap = new HashMap<String, ArrayList<String>>();
private HashMap<String, ArrayList<String>> messageMap = new HashMap<String, ArrayList<String>>();
// Stores the username for the logged in user
public void storeUsername(String user) {
username = user;
}
// Stores the recipient name
public void storeRecipient(String name) {
recipient = name;
}
// Returns how many messages the logged in user has
public int messagesNumber() {
if(messageMap.containsKey(username))
return messageMap.get(username).size();
else
return 0;
}
public boolean append(String recipient, String message) {
boolean success = false;
// If there is an entry for that name, just add the message to the end
if(messageMap.containsKey(recipient)) {
senderMap.get(recipient).add(username);
messageMap.get(recipient).add(message);
success = true;
}
// If there is no entry for that name, create a new entry with a list of messages and add the first message
else {
senderMap.put(recipient, new ArrayList<String>());
senderMap.get(recipient).add(username);
messageMap.put(recipient, new ArrayList<String>());
messageMap.get(recipient).add(message);
success = true;
}
return success;
}
public String readSender() {
// If the user has an entry and has at least 1 sender, return the least recent sender and then remove it (the sender first in the list)
if(senderMap.containsKey(username)) {
if(senderMap.get(username).size() > 0) {
String temp = senderMap.get(username).get(0);
senderMap.get(username).remove(0);
return temp;
}
else
// If there are no messages left to read
return "NO MESSAGES";
}
else
// If the login hasn't been created yet
return "NO MESSAGES";
}
public String readMessage() {
// If the user has an entry and has at least 1 unread message, return the least recent unread message and then remove it (the first message in the list)
if(messageMap.containsKey(username)) {
if(messageMap.get(username).size() > 0) {
String temp = messageMap.get(username).get(0);
messageMap.get(username).remove(0);
return temp;
}
else
// If there are no messages left to read
return "NO MESSAGES";
}
else
// If the login hasn't been created yet
return "NO MESSAGES";
}
}
I am trying to do an extra credit assignment for my Java class where we are attempting to hack into a server. The problem I am having right now is only sending one password at a time:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private static int passwordLength;
private static String attempt;
private static int counter = 0;
private static String acceptable = "ABCDEFGHIJKLMNOPQRSTUVWXYXZabcdefghijklmnopqrstuvwxyz0123456789";
public Client()
{
try
{
System.out.println("Connecting to server...");
socket = new Socket("localhost", 58999);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e)
{
System.out.println("Run the server first.");
}
}
public void close()
{
try
{
socket.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
public String sendPassword(String pass)
{
if (!HUSH) System.out.print("Sending: " + pass);
out.println(pass);
String result = null;
try
{
result = in.readLine();
if (!HUSH)
{
if (result.equals("no"))
System.out.println(" (wrong password)");
else if (result.equals("yes"))
System.out.println(" (CORRECT!)");
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
return result;
}
public static boolean HUSH = false;
public static void main(String[] args)
{
Client me = new Client();
//BEGIN YOUR WORK
int length;
HUSH = false; //change this to false for testing
System.out.println("Input character length");
Scanner ui = new Scanner(System.in);
length = ui.nextInt();
Client(length);//set the max length of the password
generate();//pull into the first generate method
me.sendPassword("1234");
me.sendPassword(attempt); //the first password i am trying to break
me.sendPassword("letmein");
me.sendPassword("willthiswork");
// END YOUR WORK
me.close();
}
public static void Client(int max)
{
passwordLength = max;
}
public static void generate()
{
generate(""); //enters generate(String password)
}
static void generate(String password)
{
//base case
if(password.length() == passwordLength)//if password is long enough
System.out.println(++counter + " " + password);
else
for(int x = 0; x < acceptable.length(); x++)
generate(attempt = password + acceptable.charAt(x));
}
}
When I run the code (using the server that is supplied), it runs every possible password combination, but returns 9 (passwordLength number of times) instead of sending say..... A (wrong password) B (wrong password) so on and so forth. I know I need to add something onto my for loop to call it back to main, but I'm not sure how to.