Application of Threads:
In a network, a server has to render its service to several clients at a time.So by using threads at server side programs,we can make the threads serve several clients at a time.
Program:
Server Side Program:
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
*/
/**
* @author Abhinaw.Tripathi
*
*/
class MultiServe implements Runnable
{
static ServerSocket ss;
static Socket s;
@Override
public void run()
{
String name=Thread.currentThread().getName();
for(;;)
{
try
{
System.out.println("Thread Name:"+name + "ready to accept....");
s=ss.accept();
System.out.println("Thread Name:"+name + " accept a connection....");
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println("Thread "+name + " contacted you");
ps.close();
s.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public class MultiServerApp
{
public static void main(String[] args) throws Exception
{
MultiServe ms=new MultiServe();
ServerSocket ss = new ServerSocket(999);
Thread t1=new Thread(ms, "One");
Thread t2=new Thread(ms, "Two");
t1.start();
t2.start();
}
}
Client Side Program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/**
*
*/
/**
* @author Abhinaw.Tripathi
*
*/
public class MultiClient
{
public static void main(String[] args) throws IOException
{
Socket s=new Socket("localhost", 999);
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
boolean str;
while(str=br.readLine() !=null)
System.out.println(str);
br.close();
s.close();
}
}