简体   繁体   中英

Reading from a socket not waiting for input?

I'm trying to do some Socket programming in Java, and I'm using the BufferedStreamReader.read(char[]) method.

the java doc states:

Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

Only it's not blocking on input.

can somone point out the problem with the following code? Even with the line that writes to the output stream the line that prints "RCVD:" is printing but without any data after the RCVD.

public class Main {

    /**
     * @param args the command line arguments
     */
         private static Socket tcpSocket;
    public static void main(String args[]) {
        try {
            tcpSocket = new Socket("localhost", 8080);
        } catch (UnknownHostException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        new Thread(new Runnable() {

            public void run() {
                try {

                    System.out.println("Starting listening");

                    char[] dataBytes = new char[9];
                    BufferedReader netStream = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));
                    while (true) {
                        netStream.read(dataBytes);

                        System.out.println("RCVD: " + String.copyValueOf(dataBytes));
                    }
                } catch (UnknownHostException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();

        new Thread(new Runnable(){
            public void run() {
                System.out.println("Starting Writer");
               PrintWriter out = null;
                try {
                    out = new PrintWriter(tcpSocket.getOutputStream(), true);
                    for (int i = 0 ; i < 10 ; i++)
                    {
                      //  out.println("000000000");
                    }
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();

    }
}

ADDITIONAL INFO

I've tried changing the port number and the application crashes, maybe I'm connecting to something else running on the machine.

Also I am reciveing a steady stream of bytes all of which are spaces by the looks of it.

You need to look into ServerSocket . Your Socket at the moment is not actually 'listening', it's trying to connect to localhost:8080 but not actually listen on it!

You are, in fact, connecting to something else on your local machine.

Looking at the code above, it looks as if you're expecting to receive, in the socket's input stream, the data that you write into its output buffer. It looks as if you're thinking of the socket as a length of tube, with the input stream at one end of the tube and the output stream at the other end.

A socket is in fact one end of the tube, with the input stream allowing you to hear what comes down it and the output stream allowing you to "talk" into the tube.

Possibly I am confused as to what is confusing you... Does the above help ?

If you think that your reads aren't blocking, capture the result of the read method and print it. If your assumption is correct, it should be zero.

int n = netStream.read(dataBytes);
System.out.println("Read " + n + " characters.");

In any case, you need to know how many characters were read so that you can invoke copyValueOf correctly—in general, only part of the array will be filled with data from the last read. And, of course, the return value signals end-of-stream (thanks, Darron!), so you need to be checking it for sure.

I've run your code and I am able to receive and print data from the server. Test your server end to make sure it is working properly.

Just 2c on this. I'm not a socket pro, but when I do use it, I tend to rely on something a bit more in the following line for reading.

char[] dataBytes = new char[9];//tcpSocket.getReceiveBufferSize()

int result = 0;
while((result = is.read(inputData)) != -1)//check for eof, 
  //if(result > 0){//<- most probably the case anyways considering .read returned
  //display only what was received
    System.out.println("RCVD: " + String.copyValueOf(inputData,0,result));
  //}
}

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