ServerSocket

In this chapter you will learn:

  1. How to use ServerSocket to create a server
  2. Local Port Scanner

ServerSocket is for server

ServerSocket is for servers. The Socket class is for clients.

import java.io.IOException;
import java.net.ServerSocket;
//  j a v  a 2  s. c  o  m
public class MainClass {

  public static void main(String[] args) {

    try {
      ServerSocket server = new ServerSocket(0);
      System.out.println("This server runs on port " + 
                   server.getLocalPort());
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Local Port Scanner

import java.io.IOException;
import java.net.ServerSocket;
//  ja v  a  2s .  c om
public class MainClass {

  public static void main(String[] args) {

    for (int port = 1; port <= 65535; port++) {

      try {
        // the next line will fail and drop into the catch block if
        // there is already a server running on the port
        ServerSocket server = new ServerSocket(port);
      } catch (IOException ex) {
        System.out.println("There is a server on port " + port + ".");
      }
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to connect to ServerSocket
  2. How to create a hello server
  3. How to create a data server
  4. Write Float value
  5. Write Object
  6. Work with Compressed socket
Home » Java Tutorial » Socket

Socket

    Socket
    Socket creation
    Socket read
    HTTP client
    SMTP Client
    Cipher Socket
    Socket connection and thread

ServerSocket

    ServerSocket
    ServerSocket connection
    File server and client
    Thread based Server
    Time server
    SocketServer based zip server
    ServerSocketChannel
    Channel selector

SocketChannel

    SocketChannel Creation
    Read and write with SocketChannel
    SocketChannel based HTTP client
    SocketChannel Asynchronous

ServerSocketChannel

    ServerSocketChannel
    Channel selector

SSL

    SSL Client Socket
    SSL Server Socket

UDP

    DatagramSocket
    DatagramChannel
    Multicast Group

Cookie

    Cookies