Why does my code stop after the while loop?

I recently fiddled with sockets and passed 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 :)

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 doesn't print or whatever after that.

The receiving end of the socket ("server") receives the message ok and also sends the data correctly (I also use some debug messages on the socket server).

Please help me, I'm dying here!

+3


source to share


2 answers


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 read result. (you should check for -1, this is the end of the pipe). From the Javadoc ,



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

And -1

not 13

.

+4


source


I'm pretty sure your "server" process is not sending 13 characters.



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

+1


source







All Articles