Here is a simple implementation of client-server using Java. There are two java files, one for client code and one for server code. The code is quite self-explanatory.
FactorialClient.java
FactorialServer.java
FactorialClient.java
Code: Java
/*
** A TCP based client that will send the number entered by the user for factorial
** calculation to a server
** @author: Tanaz Kerawala
** @author: S Pradeep
** @date: 5/29/2007
*/
import java.io.*;
import java.net.*;
class FactorialClient
{
public static void main(String arg[])
{
int port=9999;
Socket s;
String msg="";
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
InetAddress addr=InetAddress.getByName(null);
s=new Socket(addr,port);
OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream());
PrintWriter pw=new PrintWriter(osw);
BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.print("Enter a Number : ");
String str=br.readLine();
pw.println(str);
pw.flush();
msg=br1.readLine();
System.out.println("Answer from server : ");
System.out.println(msg);
}
catch(Exception e)
{
// Ignore
}
}
}
FactorialServer.java
Code: Java
/*
** A TCP based server that will calculate the factorial for client.
** @author: Tanaz Kerawala
** @author: S Pradeep
** @date: 5/29/2007
*/
import java.io.*;
import java.net.*;
class FactorialServer implements Runnable
{
Socket s;
int id;
public static void main(String arg[])
{
int port=9999,count=0;
try
{
// create new socket
ServerSocket ss=new ServerSocket(port);
System.out.println("Waiting for client");
while(true)
{
Socket s=ss.accept();
FactorialServer serve=new FactorialServer(s,count);
// launch new thread
Thread t=new Thread(serve);
t.start();
}
}
catch(Exception e)
{
// Ignore error
System.out.println("Error");
}
}
FactorialServer(Socket s,int id)
{
this.s = s;
this.id = id;
}
public void run()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream())) ;
String str=br.readLine();
int n=Integer.parseInt(str);
int i;
long f=1;
System.out.println("Number sent by client: " + n);
for(i = 2; i <= n; i++)
f = f * i;
pw.println("Factorial is : "+f);
pw.flush();
}
catch(Exception e)
{
// Ignore error
System.out.println("Thread: Error");
}
}
}
