简体   繁体   中英

How to read from Client socket only when Client socket has sent something for Server Socket

I am doing doing multi threaded client-server architecture where the server will spawn a new thread every time a client connects.

The protocol of my communication is as follows

When Client connect to Server, a connection is setup. Every time the Client clicks the login button, the username and password will be sent from Client to Server.

Eg :

 String username=Jtextfield[0].getText();
             char[] password_char = Jpasswordfield.getPassword();

            //convert from char array to String
            String password_str = new String(password_char);

            //hash player password
            String playerhashpassword = Utility.getHash(password_str);

            //send to server for login validation
             Utility.WriteToServer(username);
             Utility.WriteToServer(playerhashpassword);

If its a invalid login, the server will reply "No". The login validation is done like this

  while (loginsuccess == false)
        {
            //if server sent something
            //then read

        playername = ReadFromClient();
        playerhashpassword = ReadFromClient();

        loginsuccess = gm.loginsuccess(playername, playerhashpassword);
        }

The problem with this snippet of code is that it will keep reading what the Client send though the Client has not send anything resulting in a NullPointerException.

How do I ReadFromClient only when the Client has send something ???

ReadFromClient

public String ReadFromClient()
    {
         String inputLine;
        try
        {
               inputLine=in.readLine();
               return inputLine;
        }
           catch(IOException e)
        {
            System.out.println("Read or write to socket failed.");
            System.exit(2);    
        }


        return "willneverreachhere";

    }

You have overlooked that readLine() can return null. You need to check it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM