Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8661571
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T16:31:40+00:00 2026-06-12T16:31:40+00:00

I’ve been having some trouble trying to send a file from a server to

  • 0

I’ve been having some trouble trying to send a file from a server to a client. I can’t seem to send the same file from the server to the client into two SEPERATE files. Instead, it just appends to the end of the first file! Any help would be appreciated.

EDIT : I’ve modified the code. I’ve modularized the file sending and recieving tasks into 2 functions ‘sendfile’ and ‘recievefile’. The error I’m getting now is that the socket is closed at the sendfile and recievefile functions after the second call. But all I’m closing is the file and the output and input streams! Perhaps closing those streams will close the socket too…? Anyways, I’ve tried NOT closing the input and output streams and what happens is – 1)nothing gets transferred to the destination file. So I just get a blankly created file at the server end. 2)The second file doesn’t even get created. Great.

Any help would, as usual, be appreciated.

Server:

package com.http.server;
import java.io.*;
import java.net.*;

public class Server
{
    public static void main(String args[])throws Exception
    {
        System.out.println("Server running...");

        /* Listen on port 5555 */

        ServerSocket server = new ServerSocket(5555);

        /* Accept the sk */

        Socket sk = server.accept();

        System.out.println("Server accepted client");


        BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
        BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));

        /* Read the filename */
        String serverlocation = "C:/Users/Arjun/Desktop/CNW model/HTTP Website/";
        String filename = serverlocation + inReader.readLine();
        if ( !filename.equals("") ){

            /* Reply back to client with READY status */

            outReader.write("READY\n");
            outReader.flush();          
        }

        sendfile(sk, filename);
        sendfile(sk, filename);

        outReader.close();
        inReader.close();


        sk.close();
        server.close();

    }

    public static void sendfile(Socket sk, String filename)
    {
        try{

            OutputStream output = sk.getOutputStream();

        FileInputStream file = new FileInputStream(filename);

        byte[] buffer = new byte[sk.getSendBufferSize()];

        int bytesRead = 0; 

        while((bytesRead = file.read(buffer))>0)
        {
            output.write(buffer,0,bytesRead);
        }

        file.close();  
        output.close();
    }
        catch (Exception ex){
            System.out.println(ex);
        }
        }





    }

Client:

package com.http.client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class Client extends JFrame implements ActionListener {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JTextField txtFile;

    public static void main(String args[]){

        /* Create and display the client form */

        Client clientForm = new Client();
        clientForm.Display();
    }

    public void Display(){

        JFrame frame = new JFrame();
        frame.setTitle("Client");

        FlowLayout layout = new FlowLayout();
        layout.setAlignment(FlowLayout.LEFT);

        JLabel lblFile = new JLabel("URL:");

        txtFile = new JTextField();
        txtFile.setPreferredSize(new Dimension(150,30));

        JButton btnTransfer = new JButton("Get");
        btnTransfer.addActionListener(this);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(layout);
        mainPanel.add(lblFile);
        mainPanel.add(txtFile);
        mainPanel.add(btnTransfer);

        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {

        /* File Open Dialog box allows the user to select a file */

        String filename=txtFile.getText();

        try{

            /* Try to connect to the server on localhost, port 5555 */

            Socket sk = new Socket("localhost", 5555);


            /* Send filename to server */

            OutputStreamWriter outreader = new OutputStreamWriter(sk.getOutputStream());
            outreader.write(filename + "\n");
            outreader.flush();

            /* Get response from server */

            BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));

            String serverStatus = inReader.readLine(); // Read the first line
            /* If server is ready, receive the file */

            while ( !serverStatus.equals("READY") ){}

                /* Create a new file in the tmp directory using the filename */

               recievefile(sk,filename);
               recievefile(sk,"xx"+filename);


                JOptionPane.showMessageDialog(this, "Transfer complete");


                inReader.close();
                outreader.close();
            sk.close();

        }
        catch (Exception ex){
            /* Catch any errors */
            JOptionPane.showMessageDialog(this, ex.getMessage());
            System.out.println(ex);
        }
    }

    public void recievefile(Socket sk, String filename)
    {
        try{

            InputStream input = sk.getInputStream();

        FileOutputStream wr = new FileOutputStream(new File("C:/tmp/" + new File(filename).getName()));

        byte[] buffer = new byte[sk.getReceiveBufferSize()];
        int bytesReceived = 0;

        while((bytesReceived = input.read(buffer))>0)
        {
            /* Write to the file */
           wr.write(buffer,0,bytesReceived);
        } 
        wr.close();
        input.close();

    }
        catch (Exception ex){
            /* Catch any errors */
            JOptionPane.showMessageDialog(this, ex.getMessage());
            System.out.println(ex);
        }

}




}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T16:31:41+00:00Added an answer on June 12, 2026 at 4:31 pm

    When you send the files, you are just appending one to the end of the other so thats how the client see them.

    You need to let the client know when to stop reading one file and start reading the second.

    The simplest approach is to send the length of the file before the file and only read exactly than amount of data.

    BTW: You cannot combine binary and text streams the way you have. This is more likely to lead to confusion. In your case you need to send binary so make everything binary with DataInputStream and DataOutputStream.


    What I had in mind is something like.

    public static void sendFile(DataOutput out, String filename) throws IOException {
        FileInputStream fis = new FileInputStream(filename);
        byte[] bytes = new byte[8192];
        try {
            long size = fis.getChannel().size();
            out.writeLong(size);
            for (int len; (len = fis.read(bytes, 0, (int) Math.min(bytes.length, size))) > 0; ) {
                out.write(bytes, 0, len);
                size -= len;
            }
            assert size == 0;
        } finally {
            fis.close();
        }
    }
    
    public void receiveFile(DataInput in, String filename) throws IOException {
        long size = in.readLong();
        FileOutputStream fos = new FileOutputStream(filename);
        byte[] bytes = new byte[8192];
        try {
            for (int len; (len = (int) Math.min(size, bytes.length)) > 0; ) {
                in.readFully(bytes, 0, len);
                fos.write(bytes, 0, len);
                size -= len;
            }
        } finally {
            fos.close();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to render a haml file in a javascript response like so:
Does anyone know how can I replace this 2 symbol below from the string
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am currently running into a problem where an element is coming back from
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.