What is the functionality of setSoTimeout and how it works?

后端 未结 3 1808
旧时难觅i
旧时难觅i 2020-12-12 19:08

I\'m trying to learn Socket by myself. I\'m little bit confused by following text from Oracle website. I have some questions regarding that. Thanks in advance for any clear

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 19:35

    This example made everything clear for me:
    As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketTimeoutException;
    
    public class SocketTest extends Thread {
      private ServerSocket serverSocket;
    
      public SocketTest() throws IOException {
        serverSocket = new ServerSocket(8008);
        serverSocket.setSoTimeout(10000);
      }
    
      public void run() {
        while (true) {
          try {
            System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
            Socket client = serverSocket.accept();
    
            System.out.println("Just connected to " + client.getRemoteSocketAddress());
            client.close();
          } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
          } catch (IOException e) {
            e.printStackTrace();
            break;
          }
        }
      }
    
      public static void main(String[] args) {
        try {
          Thread t = new SocketTest();
          t.start();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    

提交回复
热议问题