Search code examples
javasocketsnetwork-programmingserverclient

Socket and ServerSocket communication unclear


I would like someone to clear up a misconception I believe I have. I'm reading on socket programming on Java, and don't really understand what is the actual flow of things. Here are my two possible interpretations for the scenario below.

Client

  1. Instance of socket is created Socket s = new Socket("server ip", 9999);

Server

  1. ServerSocket created to accept a communication ServerSocket ss = new ServerSocket(9999);
  2. Wait for a communication Socket sss = ss.accept();


What would a diagram look like after the Server program accepts?

RED ARROWS represent final COMMUNICATION stream

Would the connections after the server accepts the client look like this? (Client communicates with the socket the server created, not the serversocket)

diagram1

Or would a diagram look like this? (Client keeps communicating with the server through the serversocket. Server commmunicates back through the socket created when accepted connection.)

enter image description here


Solution

  • A socket is an abstraction for a connection between two hosts (client and server). Once the connection is established, the client and server hosts get input and output streams from the socket and use those streams to send data to each other. (Read more detail here).

    This diagram may help to you. enter image description here

    At the Client:

    • Socket socket = new Socket("server ip", 9999);

    This makes a connection across the network.

    • InputStream in = socket.getInputStream();

    Once the connection is established get an input stream from the socket connection for reading data.

    • OutputStream out = socket.getOutputStream(); Use output stream from the socket connection to write data.

    At the server:

    • ServerSocket ss = new ServerSocket(9999);

    Initiate a listening TCP socket (server socket), that bound to known local port that listen and accept connections from clients.

    • Socket socket = ss.accept();

    Blocks the current thread until a client connects, and returns a connected Socket of the accepted connection. Note, here it returns same type of java.net.Socket as for the client. Similar to client, server can use OutputStream and InputStream from the socket to write and read data.

    Refer here for more detail.