Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client server application java

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 !!!

like image 325
Pavithra Gunasekara Avatar asked Dec 15 '25 10:12

Pavithra Gunasekara


1 Answers

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());
like image 121
jbx Avatar answered Dec 17 '25 00:12

jbx