6

I am using a BufferedInputStream to read from a socket. The BufferedInputStream reads as follows:

socketInput.read(replyBuffer, 0, 7);

It is instantiated by

socketInput = new BufferedInputStream(mySocket.getInputStream());

mySocket is defined as private Socket mySocket;

mySocket is instantiated by mySocket = new Socket(ipAddress, port);

I have verified that mySocket is connected to my device. I can send data to my device; however, I am not receiving from my device for unknown reasons but that is not the problem.

I want my BufferedInputStream to return after say 100ms if it does not read any data. Can the BufferedInputStream be setup to do this? Right now, it blocks indefinitely.

  • 1
    If you want any kind of non-blocking or timeout I/O, you should use the NIO (`java.nio`) classes, not stuff in `java.io`. – C. K. Young Aug 25 '11 at 14:35

2 Answers2

5

Specify 100ms timeout for your socket. setSoTimeout

Community
  • 1
  • 1
umbr
  • 440
  • 2
  • 4
4

It's generally a bad idea to use a buffered stream for reading from a socket, for exactly this reason: it will wait forever if it doesn't see enough data to fill its internal buffer (which is going to be larger than 7 characters!) There's no way to make it time out. Just use the SocketInputStream directly, and the problem goes away.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186