简体   繁体   English

仅当客户端套接字已为服务器套接字发送了某些内容时,才从客户端套接字读取信息

[英]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. 此代码段的问题在于,尽管客户端没有发送任何导致NullPointerException的内容,但它将继续读取客户端发送的内容。

How do I ReadFromClient only when the Client has send something ??? 仅当客户端发送了某些内容时,我才如何读取From ????

ReadFromClient 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. 您忽略了readLine()可以返回null的情况。 You need to check it. 您需要检查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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