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
Socket s = new Socket("server ip", 9999);
Server
ServerSocket ss = new ServerSocket(9999);
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)
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.)
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).
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.