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

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

    I faced similar problem. In my case client must send data periodically. I hope you have same requirement. Then I set SO_TIMEOUT socket.setSoTimeout(1000 * 60 * 5); which is throw java.net.SocketTimeoutException when specified time is expired. Then I can detect dead client easily.

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

    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 !");
    
    0 讨论(0)
提交回复
热议问题