Java API Tutorial - Java ServerSocket.getChannel()








Syntax

ServerSocket.getChannel() has the following syntax.

public ServerSocketChannel getChannel()

Example

In the following code shows how to use ServerSocket.getChannel() method.

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.channels.ServerSocketChannel;
// w w w .ja v a2  s  .  c  o m
public class Main extends Thread {
  private ServerSocket serverSocket;

  public Main () throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);    
    
    ServerSocketChannel channel = serverSocket.getChannel();

  }

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

The code above generates the following result.