Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:
JavaWorld Daily Brew

Send a file through a socket connection


Hi All,

I need to read a file using a server socket and send the file to a client socket and assemble the file at the clients end. I tried to do it several ways, but failed.

Can someone tell me how to do it. Specially assemble the bits at the clients end and recreate the file and assign to a file object.

Thanks.

Your rating: None Average: 3.7 (3 votes)

Socket connection

Go to this link and good luck.

http://www.example-code.com/java/javasocket.asp

The Client just makes a

The Client just makes a connection to the port specified on the local machine and writes the received bytes to a file as specified.

It was very helpful tutorial

It was very helpful tutorial thank you so much for sharing. This website is great.

yes it was very helpful post

yes it was very helpful post i was facing some trouble with coding but this post saved my time.

It was very helpful post

It was very helpful post thank you so much for sharing knowledge.
Regards

Vintage Bicyckes

Good approach. Some tweaks

Good approach. Some tweaks are required against:
1. hardcoded byte array size
2. infinite while loop instead of timertask

I Love Java and it was my

I Love Java and it was my favorite post.
Thank you so much for sharing.

It was very helpful tutorial

It was very helpful tutorial thank you do much for sharing.

Re:

Thank you so much for shaing interesting information.
Get Educated Scam

Ok i will check this

Ok i will check this linkCarbon Footsy

Helpful Information

It is really a helpful information.It helps me making my site much better. I use your ideas and they do a fantastic job.

Knowledgeable Article.

It is really helpful information. It can help in many things. JAVA World is really a huge platform. It is very knowledgeable. I like your working style and that is really good.

Great article

It is really a helpful article for the people who are interested in networking. I like this so much. YOu guys are doing such a great work.

Helpful Article

It is really good. I like your work so much it is really great . It helps me to get more information about new inventions. And that is wonderful.

Nice Information

It is really helpful Information. You guys are doing such a moral work to share information.

It is really Helpful

Nice article. It is really helpful .It is a bundle of knowledge, I have no words to praise it. I t is mind blowing article.

Really Knowledgeable

This article is really knowledgeable. It helps to know the new programs. It gives information about new programs made by JAVA World. It is really amazing. Your article is really informative.

Really a good information.

It is really a good article. It is very helpful . It helps to know about new programs of java world and it is really great.

IT is really helpful Article

This is really informative. It is really an amazing knowledge which you guys have shared with us. It is really helpful. It helps me in my many works. You guys are really doing a great work.

black tungsten rings

Very Informative Article

This is really an knowledgeable article. Your ideas and information is really helpful.It is really an good idea to serve data in very fast way.

tungsten carbide ring

Nice Information

This is really a helpful article.It is very informative.It has solved many problems which we normally facing when we transferring data. it is really a great information.

auto insurance comparison

Just put together an

Just put together an extremely quick and dirty couple of example classes for you.
It only demonstrates a Server which waits for the first client connection, then just sends the contents of the specified file down the stream and closes up afterwards.
The Client just makes a connection to the port specified on the local machine and writes the received bytes to a file as specified.
It's not useful in itself, but it should show you all of the bits needed. Received over a ServerSocket is the same as the other way round, once you have the instance of Socket.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

public class Server {

private int port;
private String fileName;

public Server(int port, String fileName) {
this.port = port;
this.fileName = fileName;
}

private void listen() throws IOException {
BufferedInputStream in = null;
BufferedOutputStream out = null;
Socket client = null;

try {
ServerSocket socket = new ServerSocket(port);
client = socket.accept();

out = new BufferedOutputStream(client.getOutputStream());
File f = new File(fileName);
in = new BufferedInputStream(new FileInputStream(f));

byte[] b = new byte[256];
int read = -1;
while ((read = in.read(b)) >= 0) {
out.write(b, 0, read);
}

} finally {
try {
in.close();
} catch (Exception e) {}
try {
out.close();
} catch (Exception e) {}
try {
client.close();
} catch (Exception e) {}
}
}

public static void main(String[] args) throws IOException {
new Server(15000, "image.jpg").listen();
}
}

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

private int port;
private String fileName;

public Client(int port, String fileName) {
this.port = port;
this.fileName = fileName;
}

private void connect() throws UnknownHostException, IOException {
BufferedInputStream in = null;
BufferedOutputStream out = null;
Socket socket = null;

try {
socket = new Socket("127.0.0.1", 15000);
in = new BufferedInputStream(socket
.getInputStream());

File f = new File(fileName);
out = new BufferedOutputStream(
new FileOutputStream(f));

byte[] b = new byte[256];
int read = -1;

while ((read = in.read(b)) >= 0) {
out.write(b, 0, read);
}

} finally {
try {
in.close();
} catch (Exception e) {
}
try {
out.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}

public static void main(String[] args) throws UnknownHostException,
IOException {
new Client(15000, "receivedImage.jpg").connect();
}
}

Run Server first with a file named image.jpg in the working directory (or whatever you change the name to) then run Client.

Great! Thanks

Great! Thanks

Thank you so much for shaing

Thank you so much for shaing interesting information

Free Image Hosting

yes it was very helpful post

yes it was very helpful post i was facing some trouble with coding but this post saved my time.Sci-Fi Talk

Nice post. Thanks OPC

Nice post.
Thanks
OPC

FileServer en client example

Here's what I cooked up for you. Obviously it's flawed in many ways, like selecting which file to send, where to save etc, but you'll get the point...

*** File FileServer.java ***

package fileserver;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class FileServer implements Runnable{
    private final int PORT = 25573;

    public static void main(String[] args) {
        new Thread(new FileServer() ).start();
    }

    public void run() {
        ServerSocket s = null;
        try {
            s = new ServerSocket(PORT);
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        while (s != null) {
            try {
                Socket client = s.accept();
                System.out.println("client = " + client.getInetAddress());
                new Thread( new FileServerClient(client) ).start();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class FileServerClient implements Runnable {
        private Socket socket;

        FileServerClient( Socket s) {
            socket = s;
        }

        public void run() {
            try {
                BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
                FileInputStream fileIn = new FileInputStream( "/home/warner/yoursourcefile.ext");
                byte[] buffer = new byte[8192];
                int bytesRead =0;
                while ((bytesRead = fileIn.read(buffer)) > 0) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
                out.close();
                fileIn.close();

            }
            catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    socket.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

*** File FileClient.java ***

package fileserver;

import java.net.Socket;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;

public class FileClient {
    private String hostname;
    private int port;

    public static void main(String[] args) {
        FileClient fc = new FileClient("localhost", 25573);
    }

    public FileClient(String hostname, int port) {
        this.hostname = hostname;
        this.port = port;
        connect();
    }

    private void connect() {
        Socket s = new Socket();
        try {
            s.connect( new InetSocketAddress(hostname, port) );
            InputStream in = s.getInputStream();
            FileOutputStream out = new FileOutputStream("/home/warner/your destinationfile.ext");

            byte[] buffer = new byte[8192];
            int bytesRead=0;
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            out.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                s.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

File server example

Here's what I cooked up for you. Flawed in many ways, like file selection, destination, error handling, but it works. Let me know how you get on with it...

*** FileServer.java ***

package fileserver;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class FileServer implements Runnable{
    private final int PORT = 25573;

    public static void main(String[] args) {
        new Thread(new FileServer() ).start();
    }

    public void run() {
        ServerSocket s = null;
        try {
            s = new ServerSocket(PORT);
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        while (s != null) {
            try {
                Socket client = s.accept();
                System.out.println("client = " + client.getInetAddress());
                new Thread( new FileServerClient(client) ).start();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class FileServerClient implements Runnable {
        private Socket socket;

        FileServerClient( Socket s) {
            socket = s;
        }

        public void run() {
            try {
                BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
                FileInputStream fileIn = new FileInputStream( "/home/warner/yoursourcefile.ext");
                byte[] buffer = new byte[8192];
                int bytesRead =0;
                while ((bytesRead = fileIn.read(buffer)) > 0) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
                out.close();
                fileIn.close();

            }
            catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    socket.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

*** FileClient.java ***

package fileserver;

import java.net.Socket;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;

public class FileClient {
    private String hostname;
    private int port;

    public static void main(String[] args) {
        FileClient fc = new FileClient("localhost", 25573);
    }

    public FileClient(String hostname, int port) {
        this.hostname = hostname;
        this.port = port;
        connect();
    }

    private void connect() {
        Socket s = new Socket();
        try {
            s.connect( new InetSocketAddress(hostname, port) );
            InputStream in = s.getInputStream();
            FileOutputStream out = new FileOutputStream("/home/warner/mydestinationfile.ext");

            byte[] buffer = new byte[8192];
            int bytesRead=0;
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            out.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                s.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

This post really helped me

This post really helped me so much this blog is very helpful for JAVA programmers. I am reguler visitor of this website. Thank you so much guys you provided us a very helpful plateform.
Thanks
Regards
AleemBirthday Messages
Nokia Booklet 3g Netbook

Ever tried using java.nio

Ever tried using java.nio SocketChannels? less coding and seem easier to use,

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <p> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br /> <br> <strike>
  • Lines and paragraphs break automatically.
  • Use <!--pagebreak--> to create page breaks.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
Just checking to see if you're an actual person rather than a spammer. Sorry for the inconvenience.