简体   繁体   中英

While loop fails when socket reading input in java

so I am having an issue with reading input from a client. It works completely fine whenever I am using my if statements without the while statements wrapped around it in the server class. Could anybody point me to why this may be failing?

Server class:

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

public class Server {

    public static void main(String[] args) throws Exception
    {
        Server myServer = new Server();
        myServer.run();
    }

    public void run() throws Exception
    {

        //Initializes the port the serverSocket will be on
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The Server is waiting for a client on port 9999");
        //Accepts the connection for the client socket
        Socket socket = serverSocket.accept();

        InputStreamReader ir = new InputStreamReader(socket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message = br.readLine();
        //Confirms that the message was received
        System.out.println(message);

    //When this while is here.  The match fails and it goes to the else statement.
    //Without the while statement it will work and print "Received our hello message." 
    //when the client says HELLO.

     while(message != null)
     {
            if(message.equals("HELLO"))
            {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("Received our hello message.");
            }
            else
            {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("Did not receive your hello message");
            }
        }
    }
}

Client class:

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

public class Client {

    public static void main(String[] args) throws Exception
    {
        Client myClient = new Client();
        myClient.run();
    }

    public void run() throws Exception
    {
        Socket clientSocket = new Socket("localhost", 9999);
        //Sends message to the server
        PrintStream ps = new PrintStream(clientSocket.getOutputStream());
        Scanner scan = new Scanner(System.in);
        String cMessage = scan.nextLine();
        ps.println(cMessage);
        //Reads and displays response from server
        InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message = br.readLine();
        System.out.println(message);        
    }

}

You're never modifying message inside the while loop so you have an infinite loop.

Try

while((message = br.readLine()) != null)

Your code is working just fine for sending one 'HELLO' message. However, like ^Tyler pointed out, If you want to keep sending messages you need to move 'while((message = br.readLine()) != null)' in the while loop.

You only loops at the Server side, while u forgot to loop at the Client side, I did a quick fix for you, and also help you closed your connections.

Server.java

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

public class Server {

    public static void main(String[] args) throws Exception
    {
        Server myServer = new Server();
        myServer.run();
    }

    public void run() throws Exception
    {

        //Initializes the port the serverSocket will be on
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The Server is waiting for a client on port 9999");
        //Accepts the connection for the client socket
        Socket socket = serverSocket.accept();

        InputStreamReader ir = new InputStreamReader(socket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message;
        //= br.readLine();
        //Confirms that the message was received

    //When this while is here.  The match fails and it goes to the else statement.
    //Without the while statement it will work and print "Received our hello message." 
    //when the client says HELLO.
        PrintStream ps = new PrintStream(socket.getOutputStream());
        while((message =br.readLine())!=null)
         {
             System.out.println(message);
                if(message.equals("HELLO"))
                {

                    ps.println("Received our hello message.");
                }
                if(message.equals("END"))
                {
                    ps.println("Client ended the connection");
                    break;
                }
                else
                {

                    ps.println("Did not receive your hello message");
                }
        }
        ps.close();
        br.close();
        ir.close();
        serverSocket.close();
    }
}

Client.java

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

public class Client {

    public static void main(String[] args) throws Exception
    {
        Client myClient = new Client();
        myClient.run();

    }

    public void run() throws Exception
    {
        Socket clientSocket = new Socket("localhost", 9999);
        //Sends message to the server
        PrintStream ps = new PrintStream(clientSocket.getOutputStream());
        Scanner scan = new Scanner(System.in);
        String cMessage ="";
        InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        while(!(cMessage.trim().equals("END"))){
        cMessage = scan.nextLine();
        ps.println(cMessage);
        //Reads and displays response from server
        String message = br.readLine().trim();
        System.out.println(message);
        }
        br.close();
        ir.close();
        scan.close();
        ps.close();
        clientSocket.close();
    }

}

Using a loop like you are...

String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
    sleep(in);
    if(!in.ready()){
        break;
    }
}

There is a cheater way that I figured out.

private static void sleep(BufferedReader in) throws IOException {
    long time = System.currentTimeMillis();
    while(System.currentTimeMillis()-time < 1000){
        if(in.ready()){
            break;
        }
    }       
}

This might be sloppy, but if you make a sleep method that waits an amount of time and just keep checking if the BufferedReader is "ready." If it is, you can break out, but then when you come out check again. -- Maybe you could just return a boolean instead of checking twice, but the concept is there.

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