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

后端 未结 8 1561
迷失自我
迷失自我 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: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.

提交回复
热议问题