Today we are going to create a server which is going to perform factorial of a number for its client. For this task, we are going to take the help of the JAVA programming language and its different libraries. We shall also understand how a socket server runs and connect with different clients.
We created a server socket object on the server side which is running in port number 6666 of localhost (127.0.0.1). Then we created a socket object on the client side which will try to connect to port 6666. After the arrival of a successful request from the client side, the server will accept the request creating another socket object on their side.
Finally, the connection is established. Now we will send a number from the client side to the server, and a method named, "factorial" will be called server s ide. In the end, the returned value will be printed on the client side.
Let me create our server first...
//serverimport java.io.*;import java.net.*;public class b {public static void main(String args[]) throws IOException{System.out.println("...welcome...");ServerSocket ss = new ServerSocket(6666);System.out.println("...factorial server running...");int a = 0;while(true){a=a+1;System.out.println("...client searching...");Socket sc = ss.accept();System.out.println("...client found...");DataInputStream inp = new DataInputStream(sc.getInputStream());String msg = inp.readUTF();int num = Integer.parseInt(msg);System.out.println("request-"+a+": fac(" + num+")");DataOutputStream out = new DataOutputStream(sc.getOutputStream());out.writeUTF("fac("+num+") is "+factorial(num));}}public static long factorial(int n) {long fac = 1;if (n==0 || n==1) {return fac;}else{while(n>1){fac = fac*n;n = n-1;}return fac;}}}
Now create our client...
//clientimport java.io.*;import java.net.*;public class a {public static void main(String args[]) throws IOException{Socket s = new Socket("localhost", 6666);System.out.println("...connection established...");boolean valid = false;int num = 0;while(valid != true){System.out.print("enter any number: ");BufferedReader br = new BufferedReader(new InputStreamReader(System.in));try {num = Integer.parseInt(br.readLine());valid=true;} catch (Exception e) {valid=false;System.out.println("...please enter only numbers...");}}DataOutputStream out = new DataOutputStream(s.getOutputStream());out.writeUTF(Integer.toString(num));DataInputStream inp = new DataInputStream(s.getInputStream());String msg = inp.readUTF();System.out.println("server: "+ msg);s.close();}}