saplingPro
saplingPro

Reputation: 21329

ServerSocket constructor in laymans terms

What would this statement do:

ServerSocket ss=new ServerSocket(4646);

Please explain in layman terms.

Upvotes: 0

Views: 1245

Answers (4)

Jack
Jack

Reputation: 133597

The statement effectively tells the JVM to listen on port specified (4646) for incoming connections. By itself it doesn't mean anything since you will have to take incoming connections to that port and use them to build normal Socket objects that will be then used for ingoing/outgoing data.

You could say that the ServerSocket is the object through which real TCP sockets between clients and the server are created. When you create it, the JVM hooks to the operating system telling it to dispatch connections that arrive on that port to your program.

What you typically do is something like:

public AcceptThread extends Thread {
  public void run() {
    ServerSocket ss = new ServerSocket(4646);
    while (true) {
      Socket newConnection = ss.accept();
      ClientThread thread = new ClientThread(newConnection);
      thread.start();
    }
  }
}

So that you will accept incoming connections and open a thread for them.

Upvotes: 1

lukastymo
lukastymo

Reputation: 26819

public ServerSocket(int port) throws IOException

documentation:

Creates a server socket, bound to the specified port. A port of 0 creates a socket on any free port.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359876

Straight from the ServerSocket Java docs:

Creates a server socket, bound to the specified port.

What's a server socket?

This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

Upvotes: 1

corsiKa
corsiKa

Reputation: 82579

That would bind your ServerSocket to port 4646 on the local machine.

You could then accept sockets on this connection with

// pick up server side of the socket
Socket s = ss.accept();

Now, your client can connect to your server, establishing a socket connection, like this

// pick up client side of the socket, this is in a different program (probably)
Socket connectionToServer = new Socket("myserver",4646);

Upvotes: 0

Related Questions