Java API Tutorial - Java ServerSocket.getLocalPort()








Syntax

ServerSocket.getLocalPort() has the following syntax.

public int getLocalPort()

Example

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

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
/* ww  w . j av a 2s.  c o m*/
public class Main extends Thread {
  private ServerSocket serverSocket;

  public Main(int port) throws IOException {
    serverSocket = new ServerSocket(port);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();

        System.out.println("Just connected to " + server.getRemoteSocketAddress());
        DataInputStream in = new DataInputStream(server.getInputStream());
        System.out.println(in.readUTF());

        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out
            .writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
                + "\nGoodbye!");

        server.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    int port = Integer.parseInt(args[0]);

    try {
      Thread t = new Main(port);
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}