I have gone through this program which I found in a book for Java. But I have a very basic question to which I could not find any specific answer on the internet.
My code:
I have reduced the code to all what's relevant to my question.
import java.io.*;
import java.net.*;
public class DailyS {
String s="someString";
public void go{
try{
ServerSocket S=new ServerSocket(4242); while(true)
{
Socket sock=S.accept();
//other codes, irrelevant here
}
}
catch(IOException ex) {
ex.printStackTrace();
}
} public static void main(String[] arg){
DailyS server = new DailyS();
server.go() ;
}
}
I am aware that the ServerSocket
will receive a client and assign him some other random port.
My doubt:
When will this program start running and at what point of code will it start running?
I know that java programs begin running from main()
method. But the thing is the client side program has no piece of code which creates a DailS
object. It simply connects to the Server
. The client side program is not calling the go()
in server side program. So how will the connection be completed if the go()
doesn't run. Is this managed internally by java?
Will this request for connection run the
main()
method in DS?
Client side program:
import java.io.*;
import java.net.*;
public class DailyCS
{
public void go{
try{
Socket s=new Socket("ip","port");
}
catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
DailyCS server = new DailyCS();
server.go() ;
}
}
The Client Program starts running from the main method, creates an object server
and calls go()
. go()
has the code for requesting a connection. But at no point, it creates a server side class object. It neither calls the go()
in the server side class. Then how will the connection be completed?
What is the use of main()
in server side program?
Networking 101.
A server has an open port "listening" via a ServerSocket. This listens for incoming connections.
A client also has a Socket, but it is an outgoing connection towards the server's socket. A server must be running and listening for connections in order for clients to communicate.
This server program is completely separate from the client. They share no variables unless explicitly passed through the socket connection. Just because there are similar named methods and classes, doesn't make them the same.
Both programs need the main method to actually run since this is Java. Both go methods are ran in the respective classes, but only the server socket is actually accepting connections. The client code makes a socket object and connects to the server (assuming the server code is ran before the client code).