0

I am simulating a simple chat room by creating a client and server relationship. I'm just using the Netbeans IDE to run this. When the user presses enter, whatever they typed into the IDE console is sent to the server and then echoed back.

console = new BufferedReader(new InputStreamReader(System.in));    

while (thread != null) {  
    try {  
        streamOut.writeUTF(console.readLine());
        streamOut.flush();
    } catch(IOException ioe){  
        System.out.println("Sending error: " + ioe.getMessage());
        stop();
    }
}

I am trying to create a login/register system where the user is asked to enter username and password. I want the program to pause execution until the enter key is pressed. What I currently have is cutting off the first character from what is entered for username

System.out.println("Type 1 if you are an existing user \nType 2 if you want to register");
System.in.read();
System.out.println("Username:");
System.in.read();
System.out.println("Password:");

Sample output

Connected: Socket[addr=/127.0.0.1,port=10233,localport=52932]
Type 1 if you are an existing user 
Type 2 if you want to register
2
Username:
foo
Password:
52932: oo
bar
52932: bar

1 Answer 1

1

I would do this with a BufferedReader.

Something like this:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Username: ");
String username = reader.readLine();
System.out.print("Password: ");
String password = reader.readLine();

Please note, it is bad practice to send passwords in plain text and to store them in String objects. An attacker would be able to sniff the plain text username and password without much hassle and there is a chance that the String's data could be read before it is destroyed.

Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't work for me. You have to hit enter twice before the program resumes execution. I'm only running this on my localhost so that's why I'm not encrypting
It works for me using InteliJ Idea Ultimate 2017.3 and Java 9.
After changing my program structure I got it working. My solution was to get all user info before establishing a connection with the server. I believe the problem was that I was calling .writeUTF() and .readLine() simultaneously on two instances of BufferedReaders

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.