ServerSocket: setSoTimeout(int timeout) : ServerSocket « java.net « Java by API






ServerSocket: setSoTimeout(int timeout)

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class MainClass extends Thread {
  private ServerSocket serverSocket;

  public MainClass() 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 MainClass();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
           
       








Related examples in the same category

1.new ServerSocket(int port)
2.ServerSocket: accept()
3.ServerSocket: bind(SocketAddress endpoint)
4.ServerSocket: getLocalPort()
5.ServerSocket: readUTF() and writeUTF(String str)