Using TCP/IP sockets, write a client – server program to make the client send the file name and to make the server send back the contents of the requested file if present.
Client
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
public static void
main(String args[])
{
Socket socket=null;
try
{
socket=new
Socket(InetAddress.getLocalHost().getHostName(),9912);
BufferedReader reader=new
BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer=new
PrintWriter(socket.getOutputStream(),true);
System.out.println("Enter
the file name");
Scanner s=new
Scanner(System.in);
String file=s.nextLine();
writer.println(file);
System.out.println("Reading
Client......");
String h=null;
while((h=reader.readLine())
!=null)
System.out.println(h);
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
Server
import java.io.*;
import java.net.*;
public class Server
{
public static class
ClientHandler extends Thread
{
private Socket socket;
ClientHandler(Socket
socket)
{
System.out.println("client
connected\n");
this.socket=socket;
}
public void run()
{
try{
BufferedReader reader=new
BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer=new
PrintWriter(socket.getOutputStream(),true);
String
file=reader.readLine().trim();
System.out.println("requested
file is"+file+"\n");
FileReader fp2=new
FileReader(file);
BufferedReader rr=new
BufferedReader(fp2);
String k=null;
while((k=rr.readLine())!=null)
{
writer.println(k);
}
writer.close();
rr.close();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
public static void
main(String args[])
{
final int port=9912;
try
{
ServerSocket ss=new
ServerSocket(port);
System.out.println("listening.....");
while(true)
{
Socket socket=ss.accept();
new
ClientHandler(socket).start();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Comments
Post a Comment