user3830679
user3830679

Reputation:

Why does my code stop after a while loop?

I was recently messing around with sockets and transferring data between them, when my program just stopped working after looping through InputStreamReader#read(). I have absolutely no idea why this is happening, and I would appreciate any help possible :)

Here is my code:

public class SocketClient
{
    public static void main(String[] args)
    {
        String host = "localhost";
        int port = 19999;

        String instr = "";
        System.out.println("SocketClient initialized");

        try
        {
            InetAddress address = InetAddress.getByName(host);
            Socket connection = new Socket(address, port);
            BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
            OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

            String process = "{\"processType\":\"retrieveCoin\",\"uuid\":\"82012e57-6a02-3233-8ee5-63cc5bb52cd1\"}" + (char) 13;

            System.out.println("Querying Data Server: " + process);

            osw.write(process);
            osw.flush();

            System.out.println("Sent data successfully.");

            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            System.out.println("bis");

            InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
            System.out.println("isr");

            int c;

            System.out.println("ic");

            while ((c = isr.read()) != 13)
            {
                System.out.println("iwl " + ((char) c));
                instr += ((char) c);
            }

            System.out.println("awl");

            connection.close();
            System.out.println("Recieved data: " + instr);
        }
        catch (Exception ex)
        {
            System.out.println("Exception: " + ex);
        }
    }
}

The console output is fine until the end of the while loop, as the "awl" message does not print, or anything else after that.

The recieving end of the socket (the "server") gets the message okay, and also sends the data out correctly (I'm using some debug messages on the socket server as well).

Please somebody help me, I'm dying here!

Upvotes: 3

Views: 883

Answers (2)

Johntroen
Johntroen

Reputation: 3

I'm pretty sure that your "server" process does not send the 13 character.

What you probably wanted to do is to return stuff + (char) 13

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

Presumably, the remote side never sends "\r" (or ascii 13) -

while ((c = isr.read()) != 13)
{
  System.out.println("iwl " + ((char) c));
  instr += ((char) c);
}

And so your loop is blocked waiting for the result from the read. (you should check for -1, which is end of channel). From the Javadoc,

The character read, or -1 if the end of the stream has been reached

And, -1 is not 13.

Upvotes: 3

Related Questions