Header Ads Widget

Responsive Advertisement

Socket Program: Client Requests File, Server Sends Content Back

A simple client-server communication using Java sockets. The server listens for incoming file requests, reads the requested file from the local or remote system, and sends the file's contents to the client. Meanwhile, the client sends the file path to the server, receives the contents, and prints them. Here's a breakdown:

Step 1: Server Implementation

SocketServerExample class

This class represents the socket server. It listens on a predefined port (9876) and waits for clients to request a file. If the file exists, it reads the file content and sends it back to the client.

  1. Main Server Loop:

Ø  The server listens on the port (server.accept()) and waits for client connections.

Ø  Once a client connects, it receives the file path from the client (ObjectInputStream).

Ø  If the file exists, it reads the file line by line and sends the content to the client (ObjectOutputStream).

Ø  If the file doesn't exist, it sends an error message back to the client.

java

package com.kartik.socket;

import java.io.*;

import java.net.ServerSocket;

import java.net.Socket;

 

public class SocketServerExample {

 

    private static ServerSocket server;

    private static int port = 9876; // Port to listen to client requests

 

    public static void main(String args[]) throws IOException, ClassNotFoundException {

        server = new ServerSocket(port); // Start the server

 

        // Keep listening indefinitely until an 'exit' request

        while (true) {

            System.out.println("Waiting for client request");

            Socket socket = server.accept(); // Accept client connection

 

            // Receive file path from client

            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

            String message = (String) objectInputStream.readObject();

            System.out.println("Message Received: " + message);

           

            File file = new File(message);

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());

 

            if (file.exists()) {

                // Read the file and send content to client

                BufferedReader bufferReader = new BufferedReader(new FileReader(message));

                StringBuffer stringBuffer = new StringBuffer();

                String line;

                while ((line = bufferReader.readLine()) != null) {

                    System.out.println(line);

                    stringBuffer.append(line).append(System.lineSeparator());

                }

                objectOutputStream.writeObject(stringBuffer.toString());

                bufferReader.close();

            } else {

                // File not found, send error message

                System.out.println("File not found");

                objectOutputStream.writeObject("File is not there");

            }

            objectInputStream.close();

            objectOutputStream.close();

            socket.close();

 

            // Exit server if the client sends an 'exit' message

            if (message.equalsIgnoreCase("exit")) break;

        }

 

        server.close(); // Close the server

        System.out.println("Shutting down Socket server!!");

    }

}

 

Step 2: Client Implementation

SocketClientExample class

This class takes input from the user for the file name and path. Then, it calls the server to retrieve the contents of the file.

  1. Reading Input: The user inputs the file name and file path.
  2. Calling Server: The client sends the file request to the server via a socket connection and receives the file content or error message.

java

package com.kartik.socket;

import java.io.IOException;

import java.net.UnknownHostException;

import java.util.Properties;

import java.util.Scanner;

 

public class SocketClientExample {

 

    public static void main(String[] args) throws UnknownHostException, ClassNotFoundException, IOException, InterruptedException {

        SocketClientImplement socketClientImplement = new SocketClientImplement();

        String domainName = null; // Domain name of the server

        int portNumberOfServer = 9876; // Default port number

        String fileName;

        String fileNameWithPath;

 

        // Console input for file name and path

        System.out.println("Enter the file name and path:");

        Scanner console = new Scanner(System.in);

        fileName = console.next(); // Input file name

        fileNameWithPath = console.next(); // Input file path

 

        // Call the server to get the file

        socketClientImplement.callSocketServer(domainName, portNumberOfServer, fileName, fileNameWithPath);

    }

}

 

SocketClientImplement class

This class handles the socket communication between the client and the server. It sends the file path to the server and receives the response, which could either be the file content or an error message.

java

package com.kartik.socket;

import java.io.*;

import java.net.InetAddress;

import java.net.Socket;

import java.net.UnknownHostException;

 

public class SocketClientImplement {

 

    public void callSocketServer(String domainName, int portNumberOfServer, String fileName, String filePath)

            throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {

        InetAddress host = (domainName != null) ? InetAddress.getByName(domainName) : InetAddress.getLocalHost();

        int port = (portNumberOfServer > 0) ? portNumberOfServer : 9876;

 

        // Prepare file path for the server

        String fullPath = filePathMethod(fileName, filePath);

        System.out.println("File path: " + fullPath);

 

        // Establish socket connection to server

        Socket socket = new Socket(host.getHostName(), port);

 

        // Send file path to the server

        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());

        System.out.println("Sending request to Socket Server");

        objectOutputStream.writeObject(fullPath);

 

        // Receive response from the server

        ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

        String message = (String) objectInputStream.readObject();

        System.out.println("Message: " + message);

 

        objectInputStream.close();

        objectOutputStream.close();

        socket.close();

    }

 

    public String filePathMethod(String fileName, String pathName) {

        String absoluteFilePath = pathName + (System.getProperty("os.name").toLowerCase().contains("win") ? "\\" : "/") + fileName;

        System.out.println("Final file path: " + absoluteFilePath);

        return absoluteFilePath;

    }

}

 

Execution Flow:

  1. Start the server by running SocketServerExample on a different machine or server.
  2. Start the client by running SocketClientExample, enter the file name and file path (from a remote or local machine).
  3. The server receives the file path, checks if the file exists, and sends the content back to the client. If the file is missing, it sends an error message.

  

Socket program
Socket program




Post a Comment

0 Comments