开发者

Can only read one line of input from console then nothing happens : Java

开发者 https://www.devze.com 2023-04-13 09:27 出处:网络
You can see my posted code here. My original problem was more or less solved but now I\'m running into the problem described in the question title. Here\'s the problem: After I enter a command on the

You can see my posted code here. My original problem was more or less solved but now I'm running into the problem described in the question title. Here's the problem: After I enter a command on the client side of any given client, I can't enter additional commands. The first command will work fine (minus /exit; haven't quite figured out how that should work yet), just can't do anything after that. For example, I can do /register (sign in) but after that nothing else. I can go into another instance of Client and list all the current users with /list as well (works), but again, after that I cannot enter additional commands - the console will not take them after the first one. Any idea what may be happening to cause this?

Here is about where I'm referring to (Code in its entirety):

while((keyboardInput = keyboardInputScanner.nextLine()) != null){
                System.out.println("Input '" + keyboardInput + "' read on client side.");
                if(keyboardInput.equals("/exit")){
                    socketOut.println("/exit");
                    socketOut.close();
                    socketIn.close();
                    serverSocket.close();
                }el开发者_如何学JAVAse{
                    socketOut.println(keyboardInput);
                }
                while((serverInput = socketIn.readLine()) != null){
                    System.out.println(serverInput);
                }
            }

I'm relatively sure it's something to do with not breaking out of the inner while loop, but I don't know any way around it. If I put that while loop outside of the keyboard input loop, I'll never get anything back from the server.


I think the problem is here:

while((serverInput = socketIn.readLine()) != null){
    System.out.println(serverInput);
}

This will loop indefinitely (well, until the socket is closed at the other end). You therefore never get to the second iteration of the outer loop.

You might want to either limit the response to one line, or have some other mechanism for the server to let the client know when to stop reading from socketIn (e.g. send an empty line at the end of every server response and have the client break out of the inner loop when it sees that).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号