Why isn't my application entering my if statem

2019-03-03 04:01发布

I'm trying to write a console client-server application in Java; using sockets, I currently have a simple login system and a simple command system. The login system appears to work, although it prints the "Invalid username and password" line to the client, regardless whether the user inputs correct credentials. - The connection is definitely working.

However, the command system does not seem to function at all, when the command is received by the server, it does not appear to send anything back.

So my main question is why doesn't my server send anything back to the client when the command is received?

Here is my Server:

import java.io.*;
import java.net.*;

class TCPServer2
{
public static void main(String argv[]) throws Exception
{


    ServerSocket welcomeSocket = new ServerSocket(6789);
    String[][] Login = {{"MATT","UNCP"},{"JOHN","UNCP"},{"CARL","UNCP"}};
    String Command;
    String username;
    String username1;
    String password;
    String password1;
    String cmd;
    while(true)
    {
        Socket connectionSocket = welcomeSocket.accept();
        BufferedReader inFromClient =
           new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
        username = inFromClient.readLine();
        System.out.println("\nUsername received: " + username);
        password = inFromClient.readLine();
        System.out.println("\nPassword received: " + password);
        username1=username.toUpperCase();
        password1=password.toUpperCase();


        for(int i = 0; i<Login.length; i++)
        {
            if(Login[i][0].equals(username1) && Login[i][1].equals(password1))
            {
                outToClient.writeBytes("Hello " + username1);
                outToClient.writeBytes("\nOther users registered on the server currently include: \n");

                for(int k = 0; k<Login.length; k++)
                {
                    outToClient.writeBytes(Login[k][0]);
                    }
            }
            else {
                outToClient.writeBytes("Invalid Username and/or password.\n");
            }
            }
                        BufferedReader inFromClient2 =
           new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToClient2 = new DataOutputStream(connectionSocket.getOutputStream());
        Command = inFromClient2.readLine();
        System.out.println("\nCommand received: " + Command);


if(Command.equals("listTranslations"))
{
outToClient2.writeBytes("English,Thai,Geordie,etc.");
}
else
{
if(Command.equals("getCost"))
{
outToClient2.writeBytes("£100\n");
}
else
{
outToClient2.writeBytes("Invalid Command");
}
}

}

    }
}

Here is my client:

import java.io.*;
import java.net.*;

class TCPClient2
{
public static void main(String argv[]) throws Exception
{
     String userName;
     String passWord;
     String loginInfo;
     String loginInfo2;
     String loginInfo3;
     String command;
     String commandInfo;
     String commandInfo2;

     BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
     Socket clientSocket = new Socket("localhost", 6789);
     DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
     BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

     System.out.println("Username: ");
     userName = inFromUser.readLine();
     outToServer.writeBytes(userName + "\n");

     System.out.println("Password: ");
     passWord = inFromUser.readLine();
     outToServer.writeBytes(passWord + "\n");

     loginInfo = inFromServer.readLine();
     System.out.println(loginInfo);
     loginInfo2 = inFromServer.readLine();
     System.out.println(loginInfo2);
     loginInfo3 = inFromServer.readLine();
     System.out.println(loginInfo3);

     System.out.println("Please enter a command: ");
     command = inFromUser.readLine();
     outToServer.writeBytes(command);

     commandInfo = inFromServer.readLine();
     System.out.println(commandInfo);
     commandInfo2 = inFromServer.readLine();
     System.out.println(commandInfo);



     clientSocket.close();
 }
}

This is my first time asking a question on stackoverflow, but i've browsed it a lot in the past. So I just wanted to also say thank you for the great community you provide.

2条回答
Root(大扎)
2楼-- · 2019-03-03 04:16

This is a continuation from my comment:

This is how I would do it, first I would replace this: String[][] Login = {{"MATT","UNCP"},{"JOHN","UNCP"},{"CARL","UNCP"}}; by something like so:

Map<String, String> userDetails = new HashMap<String, String>();
userDetails.put("MAT", "UNCP");
userDetails.put("JOHN","UNCP"); 
userDetails.put("CARL", "UNCP");

Then, instead of this:

 for(int i = 0; i<Login.length; i++)
        {
            if(Login[i][0].equals(username1) && Login[i][1].equals(password1))
            {
                outToClient.writeBytes("Hello " + username1);
                outToClient.writeBytes("\nOther users registered on the server currently include: \n");

                for(int k = 0; k<Login.length; k++)
                {
                    outToClient.writeBytes(Login[k][0]);
                    }
            }
            else {
                outToClient.writeBytes("Invalid Username and/or password.\n");
            }
        }

I would do this:

if (userDetails.get(username1).equals(password1))
{
    outToClient.writeBytes("Hello " + username1);
                outToClient.writeBytes("\nOther users registered on the server currently include: \n");

    for (String str : userDetails.keySet()
    {
         outToClient.writeBytes(str);
    }

}
else
{
    outToClient.writeBytes("Invalid Username and/or password.\n");
}

The way I am seeing it, the system is both working and printing the Invalid credentials string is because, assuming you provide these log in details: CARL and UNCP, you are passing the 2nd set of credentials, so your loop will check the credentials by comparing them with the first set and since they do not match, it will print the message. On the second iteration, it will see that the credentials match and will log you in.

For more information take a look at the JavaDoc. HashMap is a collection which is usually a good thing to know about, besides the usual List and Set.

查看更多
看我几分像从前
3楼-- · 2019-03-03 04:35

Im not sure if this will help you but check if you don't have to flush after each writeBytes call to really outputs data to the client.

try to add outToClient.flush();

查看更多
登录 后发表回答