0

I have a question about reading and writing from input streams related to a socket. For instance, I have

ServerSocket testie = new ServerSocket(0);
Socket putClient = new Socket("localhost",testie.getLocalPort());
InputStream is = putClient.getInputStream();
OutputStream os = putClient.getOutputStream();
os.write("testt".getBytes());
System.out.println(convertStreamToString(is));

but "testt" is oddly never printed. The method convertStreamToString is from

Read/convert an InputStream to a String

public static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Is there some flaw in my understanding of streams and sockets. I thought that if you wrote to a socket's output stream you can retrieve it from its input stream? The method just hangs indefinitely.

Community
  • 1
  • 1
user1431282
  • 6,535
  • 13
  • 51
  • 68

1 Answers1

3

If you write to a socket's output stream you can read from the remote socket's input stream. In your code you are writing to one side of the socket and then trying to read from that same side.

Unfortunately, you haven't even created the remote socket yet. The next thing you will want to do is call accept() on the ServerSocket. This will receive the connection from putClient and create a Socket. This new socket will be the server side socket. Essentially you will have the following:

//Server Thread
ServerSocket testie = new ServerSocket(0);
Socket remoteSocket = testie.accept();
remoteIs = remoteSocket.getInputStream();
remoteOs = remoteSocket.getOutputStream();
System.out.println(new Scanner(remoteIs).next());

//Client Thread
Socket putClient = new Socket("localhost",testie.getLocalPort());
InputStream is = putClient.getInputStream();
OutputStream os = putClient.getOutputStream();
os.write("testt\n".getBytes());
os.flush();

Notice that I said two different threads. The problem is that the call testie.accept() will block until it gets a connection. But also, new Socket("localhost",testie.getLocalPort()) will block until the connection is established. These calls can't be made on the same thread.

UPDATE:

It's probably worth pointing out that I'm not very confident in that convertStringToStream method. You might want to start with something simple like what I've fixed the above to (note the newline in the write call).

Pace
  • 41,875
  • 13
  • 113
  • 156