0

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);        
    }

}
3
  • 2
    what is it not working? I compiled your code and I got "Received our hello message." after I type HELLO in the Client. Commented Mar 5, 2014 at 3:00
  • It works when I take out the while loop. Except when I leave it in nothing happens after when it receives HELLO and prints it in the server window. Commented Mar 5, 2014 at 3:40
  • 1
    A good practice would be closing all your sockets and readers at the end of the program. Commented Mar 5, 2014 at 4:03

4 Answers 4

2

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

Try

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that and so when the client says HELLO.. the server receives it and prints HELLO in the server window, and then nothing happens. If I try to type anything else from client to server it does not print it was received.
@Shawn, nothing is suppose to happen, you only loop your br.readline, while you forgot to loop your ps.printline
1

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();
    }

}

1 Comment

Awesome worked perfectly... just had to add else if for the message == to BYE. Thank you for the help sir and marked as answered.
1

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.

4 Comments

Ok, so If i move it to the while statement(these 2 lines):String message = br.readLine(); System.out.println(message); it will print out Received our hello message. But then it fails to an Exception in thread "main" java.lang.NullPointerException at Server.run(line 30) and Server.main(line 9)
Shawn, You must have forgot to remove br.readLine() outside the while loop, as you're using it in while loop. That is why It just prints and does not even enter the while loop! <based on your question to tyler>
I just mentioned you should read the message in the while loop. I'll edit my post to make it clear!
also remember to loop your input at the client side.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.