开发者

ServerSocket constructor in laymans terms

What would this 开发者_C百科statement do:

ServerSocket ss=new ServerSocket(4646);

Please explain in layman terms.


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.


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.


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜