I learned that Server application makes a ServerSocket in a specific port,
ServerSocket ServerSock=new ServerSocket(9000);
and client makes a socket connection to the server application,
Socket sock=new Socket("127.0.0.1","9000");
So client knows the Ip address and port of the server, I'm confused how and when the server gets knowledge about the client. Please help.
Thanx in advance !!!
The Server is 'listening' for incoming connections from clients. Just imagine the port number as being the door number and the server is waiting at that door for guests.
So when the server application does serverSock.accept() it in fact blocks and waits for clients to arrive.
Once a client tries to connect, the accept() method will unblock itself and return another Socket instance, this time representing the client.
Through that new Socket instance you can then know who the client is. An example of your server's application code would be:
ServerSocket serverSock=new ServerSocket(9000);
Socket clientSock = serverSock.accept(); //this will wait for a client
System.out.println("Yay we have a guest! He's coming from " + clientSock.getInetAddress());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With