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

后端 未结 8 1430
迷失自我
迷失自我 2020-11-22 02:34

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 h

相关标签:
8条回答
  • 2020-11-22 02:44

    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.

    0 讨论(0)
  • 2020-11-22 02:46

    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.

    0 讨论(0)
  • 2020-11-22 02:47

    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.

    0 讨论(0)
  • 2020-11-22 02:48

    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.

    0 讨论(0)
  • 2020-11-22 02:55

    Thats how I handle it

     while(true) {
            if((receiveMessage = receiveRead.readLine()) != null ) {  
    
            System.out.println("first message same :"+receiveMessage);
            System.out.println(receiveMessage);      
    
            }
            else if(receiveRead.readLine()==null)
            {
    
            System.out.println("Client has disconected: "+sock.isClosed()); 
            System.exit(1);
             }    } 
    

    if the result.code == null

    0 讨论(0)
  • 2020-11-22 02:57

    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

    0 讨论(0)
提交回复
热议问题