Signifiance of setSoTimeout() ?

Hello there,
The documentation of Socket.setSoTimeout states:
+"...With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised..."+. Simple enough, but I dont understand it's significance. Let me explain, I did a small test using the following code:
public static void main( String[] args )
   Socket s = new Socket("72.5.124.111", 80 );
   s.setSoTimeout(9000);//9 seconds
   InputStream is = s.getInputStream();
   while( is.read(buffer) != -1 )
     System.out.println(amountRead);
}As you can see, I am waiting for a response from an HTTP server, even though I have not sent any request to it. Clearly this code is stupid and as expected, I get a SocketTimeoutException after 9 seconds.
However I remove the s.setSoTimeout() line... I get an error from the native environment exactly after 60 seconds (I counted using a stop watch!).
Now we know that Socket works on TCP/IP, and therefore retries and timeouts are handled by the protocol itself. So my question is... why would anyone need setSoTimeout()? Is it a mistake to set the Timeout less than TCP's default timeout (in my case it seems it was 60 seconds)?
Edited by: GizmoC on Apr 28, 2008 2:20 AM

Maybe I don't quite get your question, but this should be rather obvious. If you are trying to make a request to a remote server and that server is unavailable, you usually won't want to wait 60 seconds to know that. Imagine you are writing an FTP client, the user enters a server name and clicks 'connect'. Now, would you want him to wait for 60 seconds before telling him that the server could not be connected to?

Similar Messages

  • How to use setSoTimeOut() with socket ??

    HI All!
    I eagerly need to know how to use setSoTimeOut() with socket (on server side).
    Actually the scenario is that My Server accepts connection and waits for connected client to send data to it. I WANT TO KEEP, IF CLIENT DOENS'T SENDS ANY DATA TO SERVER WITHIN 5 min. THEN SERVER MUST CLOSE THE CONNECTION, BUT IF SERVER RECEIVES STILL A BYTE FROM THE CLIENT WITHIN 5 mins., THE SERVER MUST RESET CHECKING TIME OUT FOR NEXT 5 MINUTES.
    How can i do that??
    Any help with example will be appreciated!!
    Thanx in advance

    you'd have to do something like this:
    (this is all assuming you want to read Strings from the socket. setSoTimeout works for any read() call to the InputStream associated with the Socket)
    ServerSocket ss = new ServerSocket(myPort);
    Socket s = ss.accept();
    s.setSoTimeout(5*60*1000); // 5 mins * 60 secs * 1000ms
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    boolean running = true;
    while(running)
    try
    String readIn = in.readLine();
    // do whatever you want with the data read
    catch(SocketTimeoutException)
    running = false;
    Now. That's what I think needs to be done. I don't have Java on the machine I'm currently on, so I can't test/verify it, but it goes something like that.
    Good luck,
    Radish21

  • Urgent! please help: why socket.setSoTimeout(ms) doesn't work precisely

    I wanted to set timeout for the sockets accepted by server as:
    Socket socket = server.accept();
    socket.setSoTimeout(5);
    Since I want the server to process next request (another thread) as soon as read block happened on the current one, I set the timeout to be extremely short. But it doesn't work. I intentionly blocked my testing client and timed my first .read() method from server. 200 ms actually escaped, no timeout happened. What could be the problem?

    You can't really expect processors to be that fine-grained. There are multiple factors:
    1) other apps are running (such as the OS), consuming processor time as well
    2) processor speed
    3) etc.

  • Socket, setSoTimeout and SocketTimeoutException

    I am experimenting with different Socket.setSoTimeout settings while reading the inputstream with BufferedReader.readLine. I have tried to provoke a SocketTimeoutException while reading a string from the Socket.inputStream.
    I have noticed that if a timeout happens after I have flushed some strings with a BufferedWriter.write, but before I have generated a string with EOL, the BufferedReader.readLine first generates a SocketTimeoutException, and then readLine-method returns the flushed strings even though none of them had a "\n", "\r" or "\r\n".
    Now, what I have not been able to do (or at least was not aware of), is to generate a Timeout before an entire string is read by the Socket.inputStream.
    1. Is it possible that if I write "this is a test\n" that a Timeout could produce (with repetitive BufferedReader.readLine) "this i" and "s a test"?
    2. What would happen if I was using ObjectOutputStream.writeObject and ObjectInputStream.readObject?
    I have looked at the source-code of BufferedReader, but I think I could spend several days to try to understand it. If anyone has any experience or ideas regarding question 1 or 2, feel free to share them.

    Moved topic to:
    http://forum.java.sun.com/thread.jspa?threadID=666967

  • Socket.setSoTimeOut() i dont get it

    setSoTimeout
    public void setSoTimeout(int timeout)
    throws SocketExceptionEnable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
    i dont get what it means when it says block? stop? And when it says it must be vailid prior to entering the block operation where abouts is that?
    Thanks

    Some Socket methods are designed to read a known number of bytes from an input stream. If those methods read less than the specified number of bytes, they will "block", which means that Socket is incapable of performing any other task until the read method completes. This can tie up system resources by keeping connections open, and might not be something desired. To avoid this, you would set the Socket's timeout value, and after the specified interval, if the Socket is still "blocked", it will timeout. When it times out, it throws an exception, but does not close the Socket or perform any Socket-related shutdown routines; it has not been "stopped". In order to shut down the Socket, you would have to write code to catch the appropriate exception, and explicitly close the Socket in that catch block. The explanation of the Socket's behavior is intended to let you know that the timeout process that happens when you set a timeout value greater than 0 is not designed to perform any resource deallocation or Socket close actions - that responsibility is left up to the programmer to handle or delegate as they see fit.
    So basically, a Socket, when attempting to read from an input stream, will not be able to do anything else until that read completes - it "blocks" waiting for the read to complete. If the read does not complete, a method is needed to free up resources that may be associated with that Socket after a certain amount of time has passed (maybe the code is being run in an environment where system thread or connectivity resources are at a premium). By setting a timeout value on a Socket you can achieve this goal, but the responsibility for stopping or closing the Socket so that the appropriate resources are released lies with the programmer using the Socket.
    Hope this isn't too incomprehensible; I recommend looking at Sun's tutorials and documentation related to Sockets for somewhat clearer explanations and code examples.
    -dSn

  • What does the "check mark" in iTunes beside the name of the song/artist signify?

    In iTunes when "MUSIC" is selected, and the list of songs appears. Why are some songs checked and others not? What does the check mark signify or accomplish?

    Tracks without a check mark are basically ignored by iTunes but left in the library.  Some people use it for deactivating seasonal (e.g., Christmas) music when they don't want it to play but still want it in their collection.  It also won't be synced.

  • What does the wifi symbol on the bottom left of photos in iphoto signify?

    What does the wifi symbol on the bottom left of photos in iPhoto signify?  I believe that whatever this signifies is preventing me from syncing an album with my iPad and iPhone.

    It means the Photos are not in your Library but instead read from an online source.
    Regards
    TD

  • Sockets: setSoTimeout() not working with Scanner

    I'm implementing the timeout feature for a server, and I've run into a problem. My server reads from the socket input stream using a Scanner, and I've set the socket timeout using Socket's setSoTimeout() method. This is supposed to throw a SocketTimeoutException, but instead, the Scanner is throwing a NoSuchElementException first (because it's not getting the right input!) and the SocketTimeoutException never gets thrown. If I use InputStream's read(), I don't have this problem (SocketTimeoutException gets thrown properly). Here's how my code is organized:
    Accept connection.
    Set so timeout.
    Spawn thread with socket as its argument.
    - Try:
    - Decode request from the socket's input stream.
    - Catch SocketTimeoutException:
    - Send timeout message to client.
    Close connection.
    Do you know a way around this issue besides replacing Scanner with read()? Or did I do something wrong?
    Ben

    If it were me I'd catch the
    NoSuchElementException first (because it's notand add a comment saying what was going on.
    Do you know a way around this issue besides replacingNope
    Scanner with read()? Or did I do something wrong?No you haven't done anything wrong. Just catch the exception
    >
    Ben

  • Hello. I need to define a mesure in a picture: I took a picture of an object with a ruler and I want to signify to photoshop "this segment = 1 cm". How to do? Thank you!

    Hello. I need to define a mesure in a picture: I took a picture of an object with a ruler and I want to signify to photoshop "this segment = 1 cm". How to do? Thank you!

    That's a good precaution, norm.  It should be no problem is you have an object on a flat surface next to a ruler. It gets trickier in security camera frames.
    Anyway that is one example. Anne can look further into the measuring tools of  Photoshop Extended to see if it helps.
    A note on the screen resolution thing. When I calculate the screen resolution, I go into Photoshop > Preferences > Units and Rulers
    and enter it here in place of the default 72 ppi.  Then when I use View > Print Size, the on-screen rulers will match a physical ruler.
    That's if you wanted to look at the actual printed document size onscreen.
    Gene

  • When I mouseover project there is a little red number displayed what does this signify?

    When I mouseover a project in Aperture a little red number is displayed in the bottom left corner of the key photo.  It is the same number for every project in my library.  What does this signify?

    Thank you.  First time positing here, sorry forgot the details.
    Aperture 3.4.5
    Mac OS X 10.7.5
    I had just installed Aperture a few hours earlier.  I was in viewer.  I was in Library Tab.  Then selected Projects. Of course this morning it is gone, should have gotten the screen shot earlier.  But every project when I would mouse over it, it has the little 'i" in a circle in the bottom right hand.  Before it also had a little red oval with the number "201" in it in the bottom left hand corner.  Wish I had gotten the screen shot. 
    It is gone now, so any solution would only satisfy my curiosity.  Thanks for reading and posting.  I will do better with my next question  :-)

  • SetSoTimeout for blocking SocketChannel.read() doesn't work

    When I tried to perform reading in blocking mode with using NIO's SocketChannel.read() method with a desired timeout, the SocketChannel.socket().setSoTimeout() method that was called before SocketChannel().read() funtion, seemed not to work properly. The read() method blocked the thread for infinite time even if I set the timeout to any non-zero value (zero means according the manual infinite timeout).
    Here is the example code:
    SocketChannel iochan;
    ByteBuffer bb = new ByteBuffer.allocateDirect(1024);
    iochan = SocketChannel.open(new InetSocketAddress(some address, some port));
    iochan.socket().setSoTimeout(2000); //should wait max. 2 secs on next read
    iochan.read(bb); //read some data to the buffer; if none present within 2 seconds then exception should be thrown - but it never happens. The thread is blocked until some data comes or the connection is closed by the peer, for example.
    What is very interesting is that this code is OK:
    SocketChannel iochan;
    ByteBuffer bb = new ByteBuffer.allocateDirect(1024);
    iochan = SocketChannel.open(new InetSocketAddress(some address, some port));
    iochan.socket().setSoTimeout(2000); //should wait max. 2 secs on next read
    iochan.socket.getInputStream().read(); //read byte; if none present within 2 seconds then exception should be thrown - this works fine.
    As you see the same socket is used. Nonetheless, I would like to use SocketChannel methods (NIO). Can anyone help me? Why doesn't work timeouts for blocking SocketChannel methods(read(),...), whereas "classic" sockets methods are OK?
    I'm using W2K SP3, Java 1.4.1_01.

    I've run into a similar problem using DatagramSockets. Apparently socket timeouts aren't supported using the nio packages, but nowhere in the documentation is this mentioned. The following bug report gives more info:
    http://developer.java.sun.com/developer/bugParade/bugs/4614802.html
    Apparently this is not considered a bug. I do however hope this is fixed in JDK 1.5, when I understand more work is to be done on nio.
    Rob

  • I have a "to" indicated in the Mail inbox column.  Why; What does that signify?

    Why; What does that signify?

    Right click on the To header and you'll see the columns selected to be displayed in the window.  You can select or deselect any column of your choosing:

  • I use photo stills in my iMovie. I want them to last longer than a minute, but when I input 01: 45: 00, to signify one min. and 45 seconds, it doesn't accept it. What is the proper format for inputting minutes?

    I use photo stills in my iMovie. I want them to last longer than a minute, but when I input 1:45:00, to signify one minute and 45 seconds, it doesn't accept it. What's the proper way to input it?

    There are 30 frames in one second of video. So you can specify down to the frame level, which is 1/30th of a second.
    Is the Duration box switching to some other time every time you type in 1:45:00?
    For instance this is a 5 second clip plus 3 frames. To get this set properly I would type in 1:45:00, then click done. I don't know if it is different under older versions of iMovie, as I'm using iMovie '11 for thisi example.

  • DatagramSocket.setSoTimeout(int) supposed to block?

    If a DatagramSocket is waiting to receive a packet (i.e., DatagramSocket.receive(DatagramPacket) has been called), is DatagramServer.setSoTimeout(int) supposed to block until receive returns? The documentation only indicates that a call to DatagramServer.setSoTimeout(int) has no effect on the current call to receive.
    If this is the correct behavior or no one is sure, what is the proper way to request clarification in the documentation? If not, I believe I know how to report it as a bug.
    Here is a test case. The sleeps just avoid data racing and ensure that the socket is open long enough to show that it really is blocking.
    import java.net.*;
    import java.io.IOException;
    public class SoTimeoutBlockTest
        private static DatagramSocket socket;
        public static void main(String[] args) throws InterruptedException, SocketException
            socket = new DatagramSocket();
            new Thread(new Receiver()).start();
            Thread.sleep(5000);
            new Thread(new SoTimeoutSetter()).start();
            Thread.sleep(10000);
            socket.close();
        private static class Receiver implements Runnable
            public void run()
                try
                    DatagramPacket p = new DatagramPacket(new byte[2000], 2000);
                    System.out.println("Receiving");
                    socket.receive(p);
                    System.out.println("Received");
                catch (IOException e)
                    e.printStackTrace();
        private static class SoTimeoutSetter implements Runnable
            public void run()
                try
                    System.out.println("Setting timeout");
                    socket.setSoTimeout(1000);
                    System.out.println("Timeout set");
                catch (SocketException e)
                    e.printStackTrace();
    }

    It was in some code someone else wrote and I was debugging. The author was using a second DatagramSocket to send a datagram to loopback to unblock the receive method of the first DatagramSocket, and they called this method on the receiving socket before sending out the packet. I don't know why they called this method; they had indicated to me that they indeed did understand it would not affect the current call to receive. Anyhow, it was causing hang ups when trying to close everything out. It was kind of hard to track down, and I would just like to see some clarification about its behavior in the API documentation. How do I submit a request for documentation?
    Edited by: Legend_Keeper on Mar 21, 2010 2:58 PM - Clarified use of second DatagramSocket for sending

  • Problems with MulticastSocket and setSoTimeout

    I tried to use a multicast socket to read multicast packets. Everything works fine but there is one strange behaviour: if i try to set a timeout
    with:
    socket.setSoTimeout(8000);
    this call blocks for 8s. And I mean this call, not the receive() method ;-) If i try different timeout it blocks for the new timeout.
    BTW this happens with both the JDK 1.4 on Linux and Win2k
    Any ideas are appreciated
    Marcus

    This is seriously bizarre. In JDK 1.4.1 all that DatagramSocket.setSoTimeout does is set a local variable, doesn't even call the system or enter any JNI.

Maybe you are looking for

  • How do I update a waveform chart with multiple plots one point at a time?

    Hi, I am updating multiple plots one point at a time.  That is, every time I update the chart I have a value for one of the plots.  If I put in a cluster with NaN for each of the charts except the one with the data I can only get individual points on

  • After updating to iOS 8.2 calls automatically are routed to mailbox

    Hi After updating to iOS 8.2. my iPhone 6 rings only once and after that all calls are routed to the mailbox. I already rebooted by holding on/off and home. the problem is still there. any idea? thx Juergen

  • Best MacBook Pro for my needs

    I know there's tons of talk on this topic but I want to see if I can narrow it down to my specific needs. I'm debating between the high end 13" rMBP (standard config) vs high end 15" (i7' 16gb, 512gb, 750m) My primary use will be web design and heavy

  • Question about Everyone Group in SharePoint 2013

    Hi, I have couple of question about EVERYONE group below,          - As per the best practice which Group we should use instead of EVERYONE group in Sharepoint ?          - What is the difference between Everyone and All Authenticated Users Group We

  • I have not been able to activate spell checker in my new installation, help.

    I have installed the newest available version of Thunderbird by automatic download. I cannot activate the spell checker. All the apparent steps have been completed; however, there are no flags as I write and no response when I ask for check at the en