Java socket API: How to tell if a connection has been closed?












70















I am running into some issues with the Java socket API. I am trying to display the number of players currently connected to my game. It is easy to determine when a player has connected. However, it seems unnecessarily difficult to determine when a player has disconnected using the socket API.



Calling isConnected() on a socket that has been disconnected remotely always seems to return true. Similarly, calling isClosed() on a socket that has been closed remotely always seems to return false. I have read that to actually determine whether or not a socket has been closed, data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation. We would just constantly have to spam a garbage message over the network to ever know when a socket had closed.



Is there any other solution?










share|improve this question





























    70















    I am running into some issues with the Java socket API. I am trying to display the number of players currently connected to my game. It is easy to determine when a player has connected. However, it seems unnecessarily difficult to determine when a player has disconnected using the socket API.



    Calling isConnected() on a socket that has been disconnected remotely always seems to return true. Similarly, calling isClosed() on a socket that has been closed remotely always seems to return false. I have read that to actually determine whether or not a socket has been closed, data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation. We would just constantly have to spam a garbage message over the network to ever know when a socket had closed.



    Is there any other solution?










    share|improve this question



























      70












      70








      70


      48






      I am running into some issues with the Java socket API. I am trying to display the number of players currently connected to my game. It is easy to determine when a player has connected. However, it seems unnecessarily difficult to determine when a player has disconnected using the socket API.



      Calling isConnected() on a socket that has been disconnected remotely always seems to return true. Similarly, calling isClosed() on a socket that has been closed remotely always seems to return false. I have read that to actually determine whether or not a socket has been closed, data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation. We would just constantly have to spam a garbage message over the network to ever know when a socket had closed.



      Is there any other solution?










      share|improve this question
















      I am running into some issues with the Java socket API. I am trying to display the number of players currently connected to my game. It is easy to determine when a player has connected. However, it seems unnecessarily difficult to determine when a player has disconnected using the socket API.



      Calling isConnected() on a socket that has been disconnected remotely always seems to return true. Similarly, calling isClosed() on a socket that has been closed remotely always seems to return false. I have read that to actually determine whether or not a socket has been closed, data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation. We would just constantly have to spam a garbage message over the network to ever know when a socket had closed.



      Is there any other solution?







      java sockets networking client-server






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 2 '15 at 21:53









      Nayuki

      14.2k53865




      14.2k53865










      asked Apr 20 '12 at 5:20









      Dan BrouwerDan Brouwer

      351143




      351143
























          7 Answers
          7






          active

          oldest

          votes


















          146














          There is no TCP API that will tell you the current state of the connection. isConnected() and isClosed() tell you the current state of your socket. Not the same thing.




          1. isConnected() tells you whether you have connected this socket. You have, so it returns true.


          2. isClosed() tells you whether you have closed this socket. Until you have, it returns false.



          3. If the peer has closed the connection in an orderly way





            • read() returns -1


            • readLine() returns null

            • readXXX() throws EOFException for any other XXX.


            • A write will throw an IOException: 'connection reset by peer', eventually, subject to buffering delays.




          4. If the connection has dropped for any other reason, a write will throw an IOException, eventually, as above, and a read may do the same thing.


          5. If the peer is still connected but not using the connection, a read timeout can be used.


          6. Contrary to what you may read elsewhere, ClosedChannelException doesn't tell you this. [Neither does SocketException: socket closed.] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection.



          7. As a result of some experiments with Java 7 on Windows XP it also appears that if:




            • you're selecting on OP_READ


            • select() returns a value of greater than zero

            • the associated SelectionKey is already invalid (key.isValid() == false)


            it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.








          share|improve this answer





















          • 13





            It is hard to believe that the TCP protocol, which is connection oriented, can't even know the status of its connection... Do the guys that come up with this protocols drive their cars with eyes closed?

            – PedroD
            Aug 11 '14 at 12:42






          • 24





            @PedroD On the contrary: it was deliberate. Previous protocol suites such as SNA had a 'dial tone'. TCP was designed to survive a nuclear war, and, more trivially, router downs and ups: hence the complete absence of anything like a dial tone, connection status, etc.; and it is also why TCP keepalive is described in the RFCs as a controversial feature, and why it is always off by default. TCP is still with us. SNA? IPX? ISO? Not. They got it right.

            – user207421
            Aug 11 '14 at 12:50








          • 2





            I don't believe that's a good excuse for hiding this information from us. Knowing that the connection was lost doesn't necessarily mean that the protocol is less fault resistant, it always depend on what we do with that knowledge... For me the method isBound and isConnected from java are pure mock methods, they have no use, but express the need for a connection event listener... But I reiterate: knowing that the connection was lost does not make the protocol worse. Now if those protocols you're saying killed the connection as soon as they detected it was lost, that is a different story.

            – PedroD
            Aug 11 '14 at 13:02








          • 17





            @Pedro You don't understand. It isn't an 'excuse'. There is no information to withhold. There is no dial tone. TCP doesn't know whether the connection has failed until you try to do something to it. That was the fundamental design criterion.

            – user207421
            Aug 11 '14 at 22:37








          • 1





            @EJP thanks for your answer. Do you perhaps know how to check if a socket got closed without "blocking"? Using read or readLine is going to block. Is there a way to realize if the other socket got closed with the available method, it seems to return 0 instead of -1.

            – insumity
            Oct 14 '14 at 14:07



















          6














          It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.



          Also, related question






          share|improve this answer





















          • 5





            It is 'general practice' in some protocols. I note that HTTP, the most used application protocol on the planet, does not have a PING operation.

            – user207421
            Nov 2 '16 at 9:22











          • @user207421 because HTTP/1 is one shot protocol. You send request, you receive response. And you are done. Socket is closed. The Websocket extension does have PING operation, so does HTTP/2.

            – Michał Zabielski
            Sep 17 '18 at 12:25











          • I recommended heartbeating with a single byte if possible :)

            – Stefan Reich
            Dec 8 '18 at 13:48











          • @MichałZabielski It is because the designers of HTTP didn't specify it. You don't know why not. HTTP/1.1 is not a one shot protocol. The socket is not closed: HTTP connections are persistent by default. FTP, SMTP, POP3, IMAP, TLS, ... don't have heartbeats.

            – user207421
            Jan 28 at 15:58



















          2














          I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).



          If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.




          I have read that to actually determine whether or not a socket has
          been closed data must be written to the output stream and an exception
          must be caught. This seems like a really unclean way to handle this
          situation.




          If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:




          • your local system could close your socket without notifying you... that is just the implementation of Socket (i.e. it doesn't poll the hardware/driver/firmware/whatever for state change).

          • new Socket(Proxy p)... there are multiple parties (6 endpoints really) that could be closing the connection on you...


          I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.






          share|improve this answer
























          • Your local system cannot 'close your socket', with or without notifying you. Your question starting 'if your Java code did not close/disconnect the socket ...?' doesn't make any sense either.

            – user207421
            Apr 20 '12 at 6:03






          • 1





            What exactly prevents system (Linux for example) from force closing the socket? Is it still possible to do it from 'gdb' using 'call close' command?

            – Andrey Lebedenko
            Nov 2 '16 at 17:08











          • @AndreyLebedenko Nothing 'exactly prevents it', but it doesn't do it.

            – user207421
            May 16 '17 at 23:59













          • @EJB who does then?

            – Andrey Lebedenko
            May 17 '17 at 15:34











          • @AndreyLebedenko Nobody does it. Only the application can close its own sockets, unless it exits without doing so, in which case the OS will clean up.

            – user207421
            Jan 24 '18 at 6:53



















          1














          I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone!
          So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.






          share|improve this answer



















          • 2





            It can take a lot more than that, up to two hours.

            – user207421
            Apr 20 '12 at 6:06



















          0














          As @user207421 say there is no way to know the current state of the connection because of the TCP/IP Protocol Architecture Model. So the server has to notice you before closing the connection or you check it by yourself.

          This is a simple example that shows how to know the socket is closed by the server:



          sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
          socket = new Socket();
          timeout = 5000;
          socket.connect(sockAdr, timeout);
          reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
          while ((data = reader.readLine())!=null)
          log.e(TAG, "received -> " + data);
          log.e(TAG, "Socket closed !");





          share|improve this answer































            -2














            On Linux when write()ing into a socket which the other side, unknown to you, closed will provoke a SIGPIPE signal/exception however you want to call it. However if you don't want to be caught out by the SIGPIPE you can use send() with the flag MSG_NOSIGNAL. The send() call will return with -1 and in this case you can check errno which will tell you that you tried to write a broken pipe (in this case a socket) with the value EPIPE which according to errno.h is equivalent to 32. As a reaction to the EPIPE you could double back and try to reopen the socket and try to send your information again.






            share|improve this answer



















            • 6





              You should try make your answer more readable

              – Mederic
              May 31 '17 at 13:33



















            -4














            I first check that if the socket is currently NULL or not and then if it is not closed



            if(socket!=null && !socket.isClosed()){
            //good to go
            }





            share|improve this answer
























            • Did you check this answer with most votes? This seems not to be an option. Or has the API changed?

              – pirho
              Dec 7 '17 at 17:28








            • 4





              If a Socket-valued variable is null, all that means is that you've nulled it. If Socket.isClosed() is true, all it means is that you closed this socket. The question is about whether the connection has been closed by the peer, and this doesn't answer it.

              – user207421
              Jan 24 '18 at 6:56












            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10240694%2fjava-socket-api-how-to-tell-if-a-connection-has-been-closed%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            146














            There is no TCP API that will tell you the current state of the connection. isConnected() and isClosed() tell you the current state of your socket. Not the same thing.




            1. isConnected() tells you whether you have connected this socket. You have, so it returns true.


            2. isClosed() tells you whether you have closed this socket. Until you have, it returns false.



            3. If the peer has closed the connection in an orderly way





              • read() returns -1


              • readLine() returns null

              • readXXX() throws EOFException for any other XXX.


              • A write will throw an IOException: 'connection reset by peer', eventually, subject to buffering delays.




            4. If the connection has dropped for any other reason, a write will throw an IOException, eventually, as above, and a read may do the same thing.


            5. If the peer is still connected but not using the connection, a read timeout can be used.


            6. Contrary to what you may read elsewhere, ClosedChannelException doesn't tell you this. [Neither does SocketException: socket closed.] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection.



            7. As a result of some experiments with Java 7 on Windows XP it also appears that if:




              • you're selecting on OP_READ


              • select() returns a value of greater than zero

              • the associated SelectionKey is already invalid (key.isValid() == false)


              it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.








            share|improve this answer





















            • 13





              It is hard to believe that the TCP protocol, which is connection oriented, can't even know the status of its connection... Do the guys that come up with this protocols drive their cars with eyes closed?

              – PedroD
              Aug 11 '14 at 12:42






            • 24





              @PedroD On the contrary: it was deliberate. Previous protocol suites such as SNA had a 'dial tone'. TCP was designed to survive a nuclear war, and, more trivially, router downs and ups: hence the complete absence of anything like a dial tone, connection status, etc.; and it is also why TCP keepalive is described in the RFCs as a controversial feature, and why it is always off by default. TCP is still with us. SNA? IPX? ISO? Not. They got it right.

              – user207421
              Aug 11 '14 at 12:50








            • 2





              I don't believe that's a good excuse for hiding this information from us. Knowing that the connection was lost doesn't necessarily mean that the protocol is less fault resistant, it always depend on what we do with that knowledge... For me the method isBound and isConnected from java are pure mock methods, they have no use, but express the need for a connection event listener... But I reiterate: knowing that the connection was lost does not make the protocol worse. Now if those protocols you're saying killed the connection as soon as they detected it was lost, that is a different story.

              – PedroD
              Aug 11 '14 at 13:02








            • 17





              @Pedro You don't understand. It isn't an 'excuse'. There is no information to withhold. There is no dial tone. TCP doesn't know whether the connection has failed until you try to do something to it. That was the fundamental design criterion.

              – user207421
              Aug 11 '14 at 22:37








            • 1





              @EJP thanks for your answer. Do you perhaps know how to check if a socket got closed without "blocking"? Using read or readLine is going to block. Is there a way to realize if the other socket got closed with the available method, it seems to return 0 instead of -1.

              – insumity
              Oct 14 '14 at 14:07
















            146














            There is no TCP API that will tell you the current state of the connection. isConnected() and isClosed() tell you the current state of your socket. Not the same thing.




            1. isConnected() tells you whether you have connected this socket. You have, so it returns true.


            2. isClosed() tells you whether you have closed this socket. Until you have, it returns false.



            3. If the peer has closed the connection in an orderly way





              • read() returns -1


              • readLine() returns null

              • readXXX() throws EOFException for any other XXX.


              • A write will throw an IOException: 'connection reset by peer', eventually, subject to buffering delays.




            4. If the connection has dropped for any other reason, a write will throw an IOException, eventually, as above, and a read may do the same thing.


            5. If the peer is still connected but not using the connection, a read timeout can be used.


            6. Contrary to what you may read elsewhere, ClosedChannelException doesn't tell you this. [Neither does SocketException: socket closed.] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection.



            7. As a result of some experiments with Java 7 on Windows XP it also appears that if:




              • you're selecting on OP_READ


              • select() returns a value of greater than zero

              • the associated SelectionKey is already invalid (key.isValid() == false)


              it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.








            share|improve this answer





















            • 13





              It is hard to believe that the TCP protocol, which is connection oriented, can't even know the status of its connection... Do the guys that come up with this protocols drive their cars with eyes closed?

              – PedroD
              Aug 11 '14 at 12:42






            • 24





              @PedroD On the contrary: it was deliberate. Previous protocol suites such as SNA had a 'dial tone'. TCP was designed to survive a nuclear war, and, more trivially, router downs and ups: hence the complete absence of anything like a dial tone, connection status, etc.; and it is also why TCP keepalive is described in the RFCs as a controversial feature, and why it is always off by default. TCP is still with us. SNA? IPX? ISO? Not. They got it right.

              – user207421
              Aug 11 '14 at 12:50








            • 2





              I don't believe that's a good excuse for hiding this information from us. Knowing that the connection was lost doesn't necessarily mean that the protocol is less fault resistant, it always depend on what we do with that knowledge... For me the method isBound and isConnected from java are pure mock methods, they have no use, but express the need for a connection event listener... But I reiterate: knowing that the connection was lost does not make the protocol worse. Now if those protocols you're saying killed the connection as soon as they detected it was lost, that is a different story.

              – PedroD
              Aug 11 '14 at 13:02








            • 17





              @Pedro You don't understand. It isn't an 'excuse'. There is no information to withhold. There is no dial tone. TCP doesn't know whether the connection has failed until you try to do something to it. That was the fundamental design criterion.

              – user207421
              Aug 11 '14 at 22:37








            • 1





              @EJP thanks for your answer. Do you perhaps know how to check if a socket got closed without "blocking"? Using read or readLine is going to block. Is there a way to realize if the other socket got closed with the available method, it seems to return 0 instead of -1.

              – insumity
              Oct 14 '14 at 14:07














            146












            146








            146







            There is no TCP API that will tell you the current state of the connection. isConnected() and isClosed() tell you the current state of your socket. Not the same thing.




            1. isConnected() tells you whether you have connected this socket. You have, so it returns true.


            2. isClosed() tells you whether you have closed this socket. Until you have, it returns false.



            3. If the peer has closed the connection in an orderly way





              • read() returns -1


              • readLine() returns null

              • readXXX() throws EOFException for any other XXX.


              • A write will throw an IOException: 'connection reset by peer', eventually, subject to buffering delays.




            4. If the connection has dropped for any other reason, a write will throw an IOException, eventually, as above, and a read may do the same thing.


            5. If the peer is still connected but not using the connection, a read timeout can be used.


            6. Contrary to what you may read elsewhere, ClosedChannelException doesn't tell you this. [Neither does SocketException: socket closed.] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection.



            7. As a result of some experiments with Java 7 on Windows XP it also appears that if:




              • you're selecting on OP_READ


              • select() returns a value of greater than zero

              • the associated SelectionKey is already invalid (key.isValid() == false)


              it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.








            share|improve this answer















            There is no TCP API that will tell you the current state of the connection. isConnected() and isClosed() tell you the current state of your socket. Not the same thing.




            1. isConnected() tells you whether you have connected this socket. You have, so it returns true.


            2. isClosed() tells you whether you have closed this socket. Until you have, it returns false.



            3. If the peer has closed the connection in an orderly way





              • read() returns -1


              • readLine() returns null

              • readXXX() throws EOFException for any other XXX.


              • A write will throw an IOException: 'connection reset by peer', eventually, subject to buffering delays.




            4. If the connection has dropped for any other reason, a write will throw an IOException, eventually, as above, and a read may do the same thing.


            5. If the peer is still connected but not using the connection, a read timeout can be used.


            6. Contrary to what you may read elsewhere, ClosedChannelException doesn't tell you this. [Neither does SocketException: socket closed.] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection.



            7. As a result of some experiments with Java 7 on Windows XP it also appears that if:




              • you're selecting on OP_READ


              • select() returns a value of greater than zero

              • the associated SelectionKey is already invalid (key.isValid() == false)


              it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.









            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 19 '16 at 0:16

























            answered Apr 20 '12 at 6:00









            user207421user207421

            264k26215363




            264k26215363








            • 13





              It is hard to believe that the TCP protocol, which is connection oriented, can't even know the status of its connection... Do the guys that come up with this protocols drive their cars with eyes closed?

              – PedroD
              Aug 11 '14 at 12:42






            • 24





              @PedroD On the contrary: it was deliberate. Previous protocol suites such as SNA had a 'dial tone'. TCP was designed to survive a nuclear war, and, more trivially, router downs and ups: hence the complete absence of anything like a dial tone, connection status, etc.; and it is also why TCP keepalive is described in the RFCs as a controversial feature, and why it is always off by default. TCP is still with us. SNA? IPX? ISO? Not. They got it right.

              – user207421
              Aug 11 '14 at 12:50








            • 2





              I don't believe that's a good excuse for hiding this information from us. Knowing that the connection was lost doesn't necessarily mean that the protocol is less fault resistant, it always depend on what we do with that knowledge... For me the method isBound and isConnected from java are pure mock methods, they have no use, but express the need for a connection event listener... But I reiterate: knowing that the connection was lost does not make the protocol worse. Now if those protocols you're saying killed the connection as soon as they detected it was lost, that is a different story.

              – PedroD
              Aug 11 '14 at 13:02








            • 17





              @Pedro You don't understand. It isn't an 'excuse'. There is no information to withhold. There is no dial tone. TCP doesn't know whether the connection has failed until you try to do something to it. That was the fundamental design criterion.

              – user207421
              Aug 11 '14 at 22:37








            • 1





              @EJP thanks for your answer. Do you perhaps know how to check if a socket got closed without "blocking"? Using read or readLine is going to block. Is there a way to realize if the other socket got closed with the available method, it seems to return 0 instead of -1.

              – insumity
              Oct 14 '14 at 14:07














            • 13





              It is hard to believe that the TCP protocol, which is connection oriented, can't even know the status of its connection... Do the guys that come up with this protocols drive their cars with eyes closed?

              – PedroD
              Aug 11 '14 at 12:42






            • 24





              @PedroD On the contrary: it was deliberate. Previous protocol suites such as SNA had a 'dial tone'. TCP was designed to survive a nuclear war, and, more trivially, router downs and ups: hence the complete absence of anything like a dial tone, connection status, etc.; and it is also why TCP keepalive is described in the RFCs as a controversial feature, and why it is always off by default. TCP is still with us. SNA? IPX? ISO? Not. They got it right.

              – user207421
              Aug 11 '14 at 12:50








            • 2





              I don't believe that's a good excuse for hiding this information from us. Knowing that the connection was lost doesn't necessarily mean that the protocol is less fault resistant, it always depend on what we do with that knowledge... For me the method isBound and isConnected from java are pure mock methods, they have no use, but express the need for a connection event listener... But I reiterate: knowing that the connection was lost does not make the protocol worse. Now if those protocols you're saying killed the connection as soon as they detected it was lost, that is a different story.

              – PedroD
              Aug 11 '14 at 13:02








            • 17





              @Pedro You don't understand. It isn't an 'excuse'. There is no information to withhold. There is no dial tone. TCP doesn't know whether the connection has failed until you try to do something to it. That was the fundamental design criterion.

              – user207421
              Aug 11 '14 at 22:37








            • 1





              @EJP thanks for your answer. Do you perhaps know how to check if a socket got closed without "blocking"? Using read or readLine is going to block. Is there a way to realize if the other socket got closed with the available method, it seems to return 0 instead of -1.

              – insumity
              Oct 14 '14 at 14:07








            13




            13





            It is hard to believe that the TCP protocol, which is connection oriented, can't even know the status of its connection... Do the guys that come up with this protocols drive their cars with eyes closed?

            – PedroD
            Aug 11 '14 at 12:42





            It is hard to believe that the TCP protocol, which is connection oriented, can't even know the status of its connection... Do the guys that come up with this protocols drive their cars with eyes closed?

            – PedroD
            Aug 11 '14 at 12:42




            24




            24





            @PedroD On the contrary: it was deliberate. Previous protocol suites such as SNA had a 'dial tone'. TCP was designed to survive a nuclear war, and, more trivially, router downs and ups: hence the complete absence of anything like a dial tone, connection status, etc.; and it is also why TCP keepalive is described in the RFCs as a controversial feature, and why it is always off by default. TCP is still with us. SNA? IPX? ISO? Not. They got it right.

            – user207421
            Aug 11 '14 at 12:50







            @PedroD On the contrary: it was deliberate. Previous protocol suites such as SNA had a 'dial tone'. TCP was designed to survive a nuclear war, and, more trivially, router downs and ups: hence the complete absence of anything like a dial tone, connection status, etc.; and it is also why TCP keepalive is described in the RFCs as a controversial feature, and why it is always off by default. TCP is still with us. SNA? IPX? ISO? Not. They got it right.

            – user207421
            Aug 11 '14 at 12:50






            2




            2





            I don't believe that's a good excuse for hiding this information from us. Knowing that the connection was lost doesn't necessarily mean that the protocol is less fault resistant, it always depend on what we do with that knowledge... For me the method isBound and isConnected from java are pure mock methods, they have no use, but express the need for a connection event listener... But I reiterate: knowing that the connection was lost does not make the protocol worse. Now if those protocols you're saying killed the connection as soon as they detected it was lost, that is a different story.

            – PedroD
            Aug 11 '14 at 13:02







            I don't believe that's a good excuse for hiding this information from us. Knowing that the connection was lost doesn't necessarily mean that the protocol is less fault resistant, it always depend on what we do with that knowledge... For me the method isBound and isConnected from java are pure mock methods, they have no use, but express the need for a connection event listener... But I reiterate: knowing that the connection was lost does not make the protocol worse. Now if those protocols you're saying killed the connection as soon as they detected it was lost, that is a different story.

            – PedroD
            Aug 11 '14 at 13:02






            17




            17





            @Pedro You don't understand. It isn't an 'excuse'. There is no information to withhold. There is no dial tone. TCP doesn't know whether the connection has failed until you try to do something to it. That was the fundamental design criterion.

            – user207421
            Aug 11 '14 at 22:37







            @Pedro You don't understand. It isn't an 'excuse'. There is no information to withhold. There is no dial tone. TCP doesn't know whether the connection has failed until you try to do something to it. That was the fundamental design criterion.

            – user207421
            Aug 11 '14 at 22:37






            1




            1





            @EJP thanks for your answer. Do you perhaps know how to check if a socket got closed without "blocking"? Using read or readLine is going to block. Is there a way to realize if the other socket got closed with the available method, it seems to return 0 instead of -1.

            – insumity
            Oct 14 '14 at 14:07





            @EJP thanks for your answer. Do you perhaps know how to check if a socket got closed without "blocking"? Using read or readLine is going to block. Is there a way to realize if the other socket got closed with the available method, it seems to return 0 instead of -1.

            – insumity
            Oct 14 '14 at 14:07













            6














            It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.



            Also, related question






            share|improve this answer





















            • 5





              It is 'general practice' in some protocols. I note that HTTP, the most used application protocol on the planet, does not have a PING operation.

              – user207421
              Nov 2 '16 at 9:22











            • @user207421 because HTTP/1 is one shot protocol. You send request, you receive response. And you are done. Socket is closed. The Websocket extension does have PING operation, so does HTTP/2.

              – Michał Zabielski
              Sep 17 '18 at 12:25











            • I recommended heartbeating with a single byte if possible :)

              – Stefan Reich
              Dec 8 '18 at 13:48











            • @MichałZabielski It is because the designers of HTTP didn't specify it. You don't know why not. HTTP/1.1 is not a one shot protocol. The socket is not closed: HTTP connections are persistent by default. FTP, SMTP, POP3, IMAP, TLS, ... don't have heartbeats.

              – user207421
              Jan 28 at 15:58
















            6














            It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.



            Also, related question






            share|improve this answer





















            • 5





              It is 'general practice' in some protocols. I note that HTTP, the most used application protocol on the planet, does not have a PING operation.

              – user207421
              Nov 2 '16 at 9:22











            • @user207421 because HTTP/1 is one shot protocol. You send request, you receive response. And you are done. Socket is closed. The Websocket extension does have PING operation, so does HTTP/2.

              – Michał Zabielski
              Sep 17 '18 at 12:25











            • I recommended heartbeating with a single byte if possible :)

              – Stefan Reich
              Dec 8 '18 at 13:48











            • @MichałZabielski It is because the designers of HTTP didn't specify it. You don't know why not. HTTP/1.1 is not a one shot protocol. The socket is not closed: HTTP connections are persistent by default. FTP, SMTP, POP3, IMAP, TLS, ... don't have heartbeats.

              – user207421
              Jan 28 at 15:58














            6












            6








            6







            It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.



            Also, related question






            share|improve this answer















            It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.



            Also, related question







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 23 '17 at 12:34









            Community

            11




            11










            answered Apr 20 '12 at 5:37









            Kalpak GadreKalpak Gadre

            4,61211528




            4,61211528








            • 5





              It is 'general practice' in some protocols. I note that HTTP, the most used application protocol on the planet, does not have a PING operation.

              – user207421
              Nov 2 '16 at 9:22











            • @user207421 because HTTP/1 is one shot protocol. You send request, you receive response. And you are done. Socket is closed. The Websocket extension does have PING operation, so does HTTP/2.

              – Michał Zabielski
              Sep 17 '18 at 12:25











            • I recommended heartbeating with a single byte if possible :)

              – Stefan Reich
              Dec 8 '18 at 13:48











            • @MichałZabielski It is because the designers of HTTP didn't specify it. You don't know why not. HTTP/1.1 is not a one shot protocol. The socket is not closed: HTTP connections are persistent by default. FTP, SMTP, POP3, IMAP, TLS, ... don't have heartbeats.

              – user207421
              Jan 28 at 15:58














            • 5





              It is 'general practice' in some protocols. I note that HTTP, the most used application protocol on the planet, does not have a PING operation.

              – user207421
              Nov 2 '16 at 9:22











            • @user207421 because HTTP/1 is one shot protocol. You send request, you receive response. And you are done. Socket is closed. The Websocket extension does have PING operation, so does HTTP/2.

              – Michał Zabielski
              Sep 17 '18 at 12:25











            • I recommended heartbeating with a single byte if possible :)

              – Stefan Reich
              Dec 8 '18 at 13:48











            • @MichałZabielski It is because the designers of HTTP didn't specify it. You don't know why not. HTTP/1.1 is not a one shot protocol. The socket is not closed: HTTP connections are persistent by default. FTP, SMTP, POP3, IMAP, TLS, ... don't have heartbeats.

              – user207421
              Jan 28 at 15:58








            5




            5





            It is 'general practice' in some protocols. I note that HTTP, the most used application protocol on the planet, does not have a PING operation.

            – user207421
            Nov 2 '16 at 9:22





            It is 'general practice' in some protocols. I note that HTTP, the most used application protocol on the planet, does not have a PING operation.

            – user207421
            Nov 2 '16 at 9:22













            @user207421 because HTTP/1 is one shot protocol. You send request, you receive response. And you are done. Socket is closed. The Websocket extension does have PING operation, so does HTTP/2.

            – Michał Zabielski
            Sep 17 '18 at 12:25





            @user207421 because HTTP/1 is one shot protocol. You send request, you receive response. And you are done. Socket is closed. The Websocket extension does have PING operation, so does HTTP/2.

            – Michał Zabielski
            Sep 17 '18 at 12:25













            I recommended heartbeating with a single byte if possible :)

            – Stefan Reich
            Dec 8 '18 at 13:48





            I recommended heartbeating with a single byte if possible :)

            – Stefan Reich
            Dec 8 '18 at 13:48













            @MichałZabielski It is because the designers of HTTP didn't specify it. You don't know why not. HTTP/1.1 is not a one shot protocol. The socket is not closed: HTTP connections are persistent by default. FTP, SMTP, POP3, IMAP, TLS, ... don't have heartbeats.

            – user207421
            Jan 28 at 15:58





            @MichałZabielski It is because the designers of HTTP didn't specify it. You don't know why not. HTTP/1.1 is not a one shot protocol. The socket is not closed: HTTP connections are persistent by default. FTP, SMTP, POP3, IMAP, TLS, ... don't have heartbeats.

            – user207421
            Jan 28 at 15:58











            2














            I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).



            If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.




            I have read that to actually determine whether or not a socket has
            been closed data must be written to the output stream and an exception
            must be caught. This seems like a really unclean way to handle this
            situation.




            If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:




            • your local system could close your socket without notifying you... that is just the implementation of Socket (i.e. it doesn't poll the hardware/driver/firmware/whatever for state change).

            • new Socket(Proxy p)... there are multiple parties (6 endpoints really) that could be closing the connection on you...


            I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.






            share|improve this answer
























            • Your local system cannot 'close your socket', with or without notifying you. Your question starting 'if your Java code did not close/disconnect the socket ...?' doesn't make any sense either.

              – user207421
              Apr 20 '12 at 6:03






            • 1





              What exactly prevents system (Linux for example) from force closing the socket? Is it still possible to do it from 'gdb' using 'call close' command?

              – Andrey Lebedenko
              Nov 2 '16 at 17:08











            • @AndreyLebedenko Nothing 'exactly prevents it', but it doesn't do it.

              – user207421
              May 16 '17 at 23:59













            • @EJB who does then?

              – Andrey Lebedenko
              May 17 '17 at 15:34











            • @AndreyLebedenko Nobody does it. Only the application can close its own sockets, unless it exits without doing so, in which case the OS will clean up.

              – user207421
              Jan 24 '18 at 6:53
















            2














            I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).



            If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.




            I have read that to actually determine whether or not a socket has
            been closed data must be written to the output stream and an exception
            must be caught. This seems like a really unclean way to handle this
            situation.




            If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:




            • your local system could close your socket without notifying you... that is just the implementation of Socket (i.e. it doesn't poll the hardware/driver/firmware/whatever for state change).

            • new Socket(Proxy p)... there are multiple parties (6 endpoints really) that could be closing the connection on you...


            I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.






            share|improve this answer
























            • Your local system cannot 'close your socket', with or without notifying you. Your question starting 'if your Java code did not close/disconnect the socket ...?' doesn't make any sense either.

              – user207421
              Apr 20 '12 at 6:03






            • 1





              What exactly prevents system (Linux for example) from force closing the socket? Is it still possible to do it from 'gdb' using 'call close' command?

              – Andrey Lebedenko
              Nov 2 '16 at 17:08











            • @AndreyLebedenko Nothing 'exactly prevents it', but it doesn't do it.

              – user207421
              May 16 '17 at 23:59













            • @EJB who does then?

              – Andrey Lebedenko
              May 17 '17 at 15:34











            • @AndreyLebedenko Nobody does it. Only the application can close its own sockets, unless it exits without doing so, in which case the OS will clean up.

              – user207421
              Jan 24 '18 at 6:53














            2












            2








            2







            I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).



            If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.




            I have read that to actually determine whether or not a socket has
            been closed data must be written to the output stream and an exception
            must be caught. This seems like a really unclean way to handle this
            situation.




            If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:




            • your local system could close your socket without notifying you... that is just the implementation of Socket (i.e. it doesn't poll the hardware/driver/firmware/whatever for state change).

            • new Socket(Proxy p)... there are multiple parties (6 endpoints really) that could be closing the connection on you...


            I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.






            share|improve this answer













            I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).



            If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.




            I have read that to actually determine whether or not a socket has
            been closed data must be written to the output stream and an exception
            must be caught. This seems like a really unclean way to handle this
            situation.




            If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:




            • your local system could close your socket without notifying you... that is just the implementation of Socket (i.e. it doesn't poll the hardware/driver/firmware/whatever for state change).

            • new Socket(Proxy p)... there are multiple parties (6 endpoints really) that could be closing the connection on you...


            I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 20 '12 at 5:40









            ScottleyScottley

            815




            815













            • Your local system cannot 'close your socket', with or without notifying you. Your question starting 'if your Java code did not close/disconnect the socket ...?' doesn't make any sense either.

              – user207421
              Apr 20 '12 at 6:03






            • 1





              What exactly prevents system (Linux for example) from force closing the socket? Is it still possible to do it from 'gdb' using 'call close' command?

              – Andrey Lebedenko
              Nov 2 '16 at 17:08











            • @AndreyLebedenko Nothing 'exactly prevents it', but it doesn't do it.

              – user207421
              May 16 '17 at 23:59













            • @EJB who does then?

              – Andrey Lebedenko
              May 17 '17 at 15:34











            • @AndreyLebedenko Nobody does it. Only the application can close its own sockets, unless it exits without doing so, in which case the OS will clean up.

              – user207421
              Jan 24 '18 at 6:53



















            • Your local system cannot 'close your socket', with or without notifying you. Your question starting 'if your Java code did not close/disconnect the socket ...?' doesn't make any sense either.

              – user207421
              Apr 20 '12 at 6:03






            • 1





              What exactly prevents system (Linux for example) from force closing the socket? Is it still possible to do it from 'gdb' using 'call close' command?

              – Andrey Lebedenko
              Nov 2 '16 at 17:08











            • @AndreyLebedenko Nothing 'exactly prevents it', but it doesn't do it.

              – user207421
              May 16 '17 at 23:59













            • @EJB who does then?

              – Andrey Lebedenko
              May 17 '17 at 15:34











            • @AndreyLebedenko Nobody does it. Only the application can close its own sockets, unless it exits without doing so, in which case the OS will clean up.

              – user207421
              Jan 24 '18 at 6:53

















            Your local system cannot 'close your socket', with or without notifying you. Your question starting 'if your Java code did not close/disconnect the socket ...?' doesn't make any sense either.

            – user207421
            Apr 20 '12 at 6:03





            Your local system cannot 'close your socket', with or without notifying you. Your question starting 'if your Java code did not close/disconnect the socket ...?' doesn't make any sense either.

            – user207421
            Apr 20 '12 at 6:03




            1




            1





            What exactly prevents system (Linux for example) from force closing the socket? Is it still possible to do it from 'gdb' using 'call close' command?

            – Andrey Lebedenko
            Nov 2 '16 at 17:08





            What exactly prevents system (Linux for example) from force closing the socket? Is it still possible to do it from 'gdb' using 'call close' command?

            – Andrey Lebedenko
            Nov 2 '16 at 17:08













            @AndreyLebedenko Nothing 'exactly prevents it', but it doesn't do it.

            – user207421
            May 16 '17 at 23:59







            @AndreyLebedenko Nothing 'exactly prevents it', but it doesn't do it.

            – user207421
            May 16 '17 at 23:59















            @EJB who does then?

            – Andrey Lebedenko
            May 17 '17 at 15:34





            @EJB who does then?

            – Andrey Lebedenko
            May 17 '17 at 15:34













            @AndreyLebedenko Nobody does it. Only the application can close its own sockets, unless it exits without doing so, in which case the OS will clean up.

            – user207421
            Jan 24 '18 at 6:53





            @AndreyLebedenko Nobody does it. Only the application can close its own sockets, unless it exits without doing so, in which case the OS will clean up.

            – user207421
            Jan 24 '18 at 6:53











            1














            I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone!
            So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.






            share|improve this answer



















            • 2





              It can take a lot more than that, up to two hours.

              – user207421
              Apr 20 '12 at 6:06
















            1














            I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone!
            So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.






            share|improve this answer



















            • 2





              It can take a lot more than that, up to two hours.

              – user207421
              Apr 20 '12 at 6:06














            1












            1








            1







            I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone!
            So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.






            share|improve this answer













            I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone!
            So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 20 '12 at 5:55









            Ehsan KhodarahmiEhsan Khodarahmi

            2,67174874




            2,67174874








            • 2





              It can take a lot more than that, up to two hours.

              – user207421
              Apr 20 '12 at 6:06














            • 2





              It can take a lot more than that, up to two hours.

              – user207421
              Apr 20 '12 at 6:06








            2




            2





            It can take a lot more than that, up to two hours.

            – user207421
            Apr 20 '12 at 6:06





            It can take a lot more than that, up to two hours.

            – user207421
            Apr 20 '12 at 6:06











            0














            As @user207421 say there is no way to know the current state of the connection because of the TCP/IP Protocol Architecture Model. So the server has to notice you before closing the connection or you check it by yourself.

            This is a simple example that shows how to know the socket is closed by the server:



            sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
            socket = new Socket();
            timeout = 5000;
            socket.connect(sockAdr, timeout);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
            while ((data = reader.readLine())!=null)
            log.e(TAG, "received -> " + data);
            log.e(TAG, "Socket closed !");





            share|improve this answer




























              0














              As @user207421 say there is no way to know the current state of the connection because of the TCP/IP Protocol Architecture Model. So the server has to notice you before closing the connection or you check it by yourself.

              This is a simple example that shows how to know the socket is closed by the server:



              sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
              socket = new Socket();
              timeout = 5000;
              socket.connect(sockAdr, timeout);
              reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
              while ((data = reader.readLine())!=null)
              log.e(TAG, "received -> " + data);
              log.e(TAG, "Socket closed !");





              share|improve this answer


























                0












                0








                0







                As @user207421 say there is no way to know the current state of the connection because of the TCP/IP Protocol Architecture Model. So the server has to notice you before closing the connection or you check it by yourself.

                This is a simple example that shows how to know the socket is closed by the server:



                sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
                socket = new Socket();
                timeout = 5000;
                socket.connect(sockAdr, timeout);
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
                while ((data = reader.readLine())!=null)
                log.e(TAG, "received -> " + data);
                log.e(TAG, "Socket closed !");





                share|improve this answer













                As @user207421 say there is no way to know the current state of the connection because of the TCP/IP Protocol Architecture Model. So the server has to notice you before closing the connection or you check it by yourself.

                This is a simple example that shows how to know the socket is closed by the server:



                sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
                socket = new Socket();
                timeout = 5000;
                socket.connect(sockAdr, timeout);
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
                while ((data = reader.readLine())!=null)
                log.e(TAG, "received -> " + data);
                log.e(TAG, "Socket closed !");






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 3 at 12:29









                ucMediaucMedia

                1,2963927




                1,2963927























                    -2














                    On Linux when write()ing into a socket which the other side, unknown to you, closed will provoke a SIGPIPE signal/exception however you want to call it. However if you don't want to be caught out by the SIGPIPE you can use send() with the flag MSG_NOSIGNAL. The send() call will return with -1 and in this case you can check errno which will tell you that you tried to write a broken pipe (in this case a socket) with the value EPIPE which according to errno.h is equivalent to 32. As a reaction to the EPIPE you could double back and try to reopen the socket and try to send your information again.






                    share|improve this answer



















                    • 6





                      You should try make your answer more readable

                      – Mederic
                      May 31 '17 at 13:33
















                    -2














                    On Linux when write()ing into a socket which the other side, unknown to you, closed will provoke a SIGPIPE signal/exception however you want to call it. However if you don't want to be caught out by the SIGPIPE you can use send() with the flag MSG_NOSIGNAL. The send() call will return with -1 and in this case you can check errno which will tell you that you tried to write a broken pipe (in this case a socket) with the value EPIPE which according to errno.h is equivalent to 32. As a reaction to the EPIPE you could double back and try to reopen the socket and try to send your information again.






                    share|improve this answer



















                    • 6





                      You should try make your answer more readable

                      – Mederic
                      May 31 '17 at 13:33














                    -2












                    -2








                    -2







                    On Linux when write()ing into a socket which the other side, unknown to you, closed will provoke a SIGPIPE signal/exception however you want to call it. However if you don't want to be caught out by the SIGPIPE you can use send() with the flag MSG_NOSIGNAL. The send() call will return with -1 and in this case you can check errno which will tell you that you tried to write a broken pipe (in this case a socket) with the value EPIPE which according to errno.h is equivalent to 32. As a reaction to the EPIPE you could double back and try to reopen the socket and try to send your information again.






                    share|improve this answer













                    On Linux when write()ing into a socket which the other side, unknown to you, closed will provoke a SIGPIPE signal/exception however you want to call it. However if you don't want to be caught out by the SIGPIPE you can use send() with the flag MSG_NOSIGNAL. The send() call will return with -1 and in this case you can check errno which will tell you that you tried to write a broken pipe (in this case a socket) with the value EPIPE which according to errno.h is equivalent to 32. As a reaction to the EPIPE you could double back and try to reopen the socket and try to send your information again.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered May 31 '17 at 13:29









                    MikeKMikeK

                    7




                    7








                    • 6





                      You should try make your answer more readable

                      – Mederic
                      May 31 '17 at 13:33














                    • 6





                      You should try make your answer more readable

                      – Mederic
                      May 31 '17 at 13:33








                    6




                    6





                    You should try make your answer more readable

                    – Mederic
                    May 31 '17 at 13:33





                    You should try make your answer more readable

                    – Mederic
                    May 31 '17 at 13:33











                    -4














                    I first check that if the socket is currently NULL or not and then if it is not closed



                    if(socket!=null && !socket.isClosed()){
                    //good to go
                    }





                    share|improve this answer
























                    • Did you check this answer with most votes? This seems not to be an option. Or has the API changed?

                      – pirho
                      Dec 7 '17 at 17:28








                    • 4





                      If a Socket-valued variable is null, all that means is that you've nulled it. If Socket.isClosed() is true, all it means is that you closed this socket. The question is about whether the connection has been closed by the peer, and this doesn't answer it.

                      – user207421
                      Jan 24 '18 at 6:56
















                    -4














                    I first check that if the socket is currently NULL or not and then if it is not closed



                    if(socket!=null && !socket.isClosed()){
                    //good to go
                    }





                    share|improve this answer
























                    • Did you check this answer with most votes? This seems not to be an option. Or has the API changed?

                      – pirho
                      Dec 7 '17 at 17:28








                    • 4





                      If a Socket-valued variable is null, all that means is that you've nulled it. If Socket.isClosed() is true, all it means is that you closed this socket. The question is about whether the connection has been closed by the peer, and this doesn't answer it.

                      – user207421
                      Jan 24 '18 at 6:56














                    -4












                    -4








                    -4







                    I first check that if the socket is currently NULL or not and then if it is not closed



                    if(socket!=null && !socket.isClosed()){
                    //good to go
                    }





                    share|improve this answer













                    I first check that if the socket is currently NULL or not and then if it is not closed



                    if(socket!=null && !socket.isClosed()){
                    //good to go
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 7 '17 at 17:06









                    JiraiyaJiraiya

                    233




                    233













                    • Did you check this answer with most votes? This seems not to be an option. Or has the API changed?

                      – pirho
                      Dec 7 '17 at 17:28








                    • 4





                      If a Socket-valued variable is null, all that means is that you've nulled it. If Socket.isClosed() is true, all it means is that you closed this socket. The question is about whether the connection has been closed by the peer, and this doesn't answer it.

                      – user207421
                      Jan 24 '18 at 6:56



















                    • Did you check this answer with most votes? This seems not to be an option. Or has the API changed?

                      – pirho
                      Dec 7 '17 at 17:28








                    • 4





                      If a Socket-valued variable is null, all that means is that you've nulled it. If Socket.isClosed() is true, all it means is that you closed this socket. The question is about whether the connection has been closed by the peer, and this doesn't answer it.

                      – user207421
                      Jan 24 '18 at 6:56

















                    Did you check this answer with most votes? This seems not to be an option. Or has the API changed?

                    – pirho
                    Dec 7 '17 at 17:28







                    Did you check this answer with most votes? This seems not to be an option. Or has the API changed?

                    – pirho
                    Dec 7 '17 at 17:28






                    4




                    4





                    If a Socket-valued variable is null, all that means is that you've nulled it. If Socket.isClosed() is true, all it means is that you closed this socket. The question is about whether the connection has been closed by the peer, and this doesn't answer it.

                    – user207421
                    Jan 24 '18 at 6:56





                    If a Socket-valued variable is null, all that means is that you've nulled it. If Socket.isClosed() is true, all it means is that you closed this socket. The question is about whether the connection has been closed by the peer, and this doesn't answer it.

                    – user207421
                    Jan 24 '18 at 6:56


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10240694%2fjava-socket-api-how-to-tell-if-a-connection-has-been-closed%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas

                    Can't read property showImagePicker of undefined in react native iOS