code: private void receive() {
      try {
        Socket socket = null;
        BufferedReader reader = null;
        try {
          // connect to the server
          socket = new Socket(host, port);
          reader = new BufferedReader(
              new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
          // Until stopped or connection broken continue reading
          String userInput;
          while (!isStopped() && (userInput = reader.readLine()) != null) {
            System.out.println("Received data '" + userInput + "'");
            store(userInput);
          }
        } finally {
          Closeables.close(reader, /* swallowIOException = */ true);
          Closeables.close(socket,  /* swallowIOException = */ true);
        }
        // Restart in an attempt to connect again when server is active again
        restart("Trying to connect again");
      } catch(ConnectException ce) {
        // restart if could not connect to server
        restart("Could not connect", ce);
      } catch(Throwable t) {
        restart("Error receiving data", t);
      }
    }
docs: Create a socket connection and receive data until receiver is stopped