Documente Academic
Documente Profesional
Documente Cultură
Let the
client side request for files and the server reads it and sends to the client.
Input and Output Requirements:
The client accepts filename through the keyboard and sends it to the server. The server
reads the file and transfers the content back to the client.
Algorithm: server side
Begin
Create an object of server socket class and listen for incoming client connection in a
specified port.
When a client connection is established, create input and output streams for this connection.
While (true)
a. Read a file name from the input stream.
b. Read the content of the file requested by the client.
c. Send the file content to the client.
d. Close server and client socket.
End
import java.io.*;
import java.net.*;
do
{
try
{
filename = (String) in.readObject();
System.out.println("Server > Got filename From Client -> " + filename);
File file = new File(filename);
FileInputStream fin = new FileInputStream(file);
DataInputStream din = new DataInputStream(fin);
while((contents = din.readLine()) != null)
{
System.out.println("Inside" + contents);
serverMessage(contents); //sending file contents.....
}
if(filename.equals("bye"))
serverMessage("bye");
}
catch(ClassNotFoundException e){
System.out.println(e.getMessage());
}
}while(!filename.equals("bye"));
}
catch(IOException e){}
finally
{
try
{
in.close();
out.close();
server.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
void serverMessage(String str) throws IOException
{
try
{
out.writeObject(str); // WRITING TO SERVER'S OUTPUT
BUFFER.....
out.flush(); // clearing the output buffer.....
System.out.println("Server -writing Message to Server's output buffer....." + str);
}
catch(IOException ioe){ }
}
import java.io.*;
import java.net.*;
do
{
try
{
msg = (String)in.readObject(); System.out.println("Client
> Message From Server ->" + msg);
ClientMessage(file);
}
catch(ClassNotFoundException e){
System.out.println(e.getMessage());
}
}while(!msg.equals("bye"));
}
catch(IOException e){}
}
void ClientMessage(String str) throws IOException
{
try
{
System.out.println("Client > Writing to Client's output
buffer....." + str );
out.writeObject(str); // WRITING TO CLIENT'S OUTPUT BUFFER.....
out.flush(); // clearing the output buffer.....
}
catch(IOException ioe){}
}
public static void main(String[] args) throws UnknownHostException ,IOException
{
FTP_Client client = new FTP_Client();
client.start();
}
}
Output:
Server side
Server – listening on port 2004
Server – Waiting for the Client…..
Server > Got filename from Client -> test.txt
Client Side
Filename : test.txt
Client > Connecting to server…..
Client > message from server -> Hello I am sandeep.