Fast file transfer via sockets

Hi,
I have made little program that sends files via lan to my other computer using sockets (ServerSocket and Socket). When I code my program to use only FileInputStream and FileOutputStream throught the sockets I get only speed about 100Kbs even when I run them in localhost.
I would really like to have examples of faster way to send and receive files throught sockets? Any samples using buffers or compressing data would be very nice. Thank you very much in advance!
Sincerely,
Lauri Lehtinen

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
* FileServer.java
* Created on January 18, 2005, 2:21 PM
* @author  Ian Schneider
public class FileServer {
    static class Server {
        Socket client;
        public Server() throws Exception {
            ServerSocket s = new ServerSocket(12345);
            while (true) {
                client = s.accept();
                File dest = new File(System.getProperty("java.io.tmpdir"),"transfer.tmp");
                InputStream data = client.getInputStream();
                OutputStream out = new FileOutputStream(dest);
                byte[] bytes = new byte[1024];
                int l = 0;
                int cnt = 0;
                long time = System.currentTimeMillis();
                while ( (l = data.read(bytes)) >= 0) {
                    cnt += l;
                    out.write(bytes,0, l);
                int kb = cnt / 1024;
                int sec = (int) (System.currentTimeMillis() - time) / 1000;
                System.out.println("transfered " + kb/sec);
                out.flush();
                out.close();
                client.close();
    static void writeToServer(String fileName) throws Exception {
        Socket s = new Socket("localhost",12345);
        OutputStream out = s.getOutputStream();
        FileInputStream in = new FileInputStream(fileName);
        byte[] bytes = new byte[1024];
        int l = 0;
        while ( (l = in.read(bytes)) >= 0) {
            out.write(bytes,0,l);
        out.flush();
        out.close();
        in.close();
    public static final void main(String[] args) throws Exception {
        if (args[0].equals("server")) {
            new Server();
        } else {
            writeToServer(args[1]);
}You may see improvements by buffering these. I didn't bother testing.

Similar Messages

  • File transfer via socket problem (with source code)

    I have a problem with this simple client/server filetransfer program. When I run it, only half the file is transfered via the net? Can someone point out to me why this is happening?
    Client:
    import java.net.*;
    import java.io.*;
         public class Client {
         public static void main(String[] args) {
              // IPadressen til server
              String host = "127.0.0.1";
              int port = 4545;
              //Lager streams
              BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // Henter filen vi vil sende over sockets
              File file = new File("c:\\temp\\fileiwanttosend.jpg");
    // Sjekker om filen fins
              if (!file.exists()) {
              System.out.println("File doesn't exist");
              System.exit(0);
              try{
              // Lager ny InputStream
              fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee) {System.out.println("Problem, kunne ikke lage fil"); }
              try{
              // Lager InetAddress
              InetAddress adressen = InetAddress.getByName(host);
              try{
              System.out.println("- Lager Socket..........");
              // �pner socket
              Socket s = new Socket(adressen, port);
              System.out.println("- Socket klar.........");
              // Setter outputstream til socket
              out = new BufferedOutputStream(s.getOutputStream());
              // Leser buffer inn i tabell
              byte[] buffer = new byte[1024];
              int numRead;
              while( (numRead = fileIn.read(buffer)) >= 0) {
              // Skriver bytes til OutputStream fra 0 til totalt antall bytes
              System.out.println("Copies "+fileIn.read(buffer)+" bytes");
              out.write(buffer, 0, numRead);
              // Flush - sender fil
              out.flush();
              // Lukker OutputStream
              out.close();
              // Lukker InputStrean
              fileIn.close();
              // Lukker Socket
              s.close();
              System.out.println("File is sent to: "+host);
              catch (IOException e) {
              }catch(UnknownHostException e) {
              System.err.println(e);
    Server:
    import java.net.*;
    import java.io.*;
    public class Server {
         public static void main(String[] args) {
    // Portnummer m� v�re det samme p� b�de klient og server
    int port = 4545;
         try{
              // Lager en ServerSocket
              ServerSocket server = new ServerSocket(port);
              // Lager to socketforbindelser
              Socket forbindelse1 = null;
              Socket forbindelse2 = null;
         while (true) {
         try{
              forbindelse1 = server.accept();
              System.out.println("Server accepts");
              BufferedInputStream inn = new BufferedInputStream(forbindelse1.getInputStream());
              BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:\\temp\\file.jpg")));
              byte[] buff = new byte[1024];
              int readMe;
              while( (readMe = inn.read(buff)) >= 0) {
              // Skriver filen til disken ut fra input stream
              ut.write(buff, 0, readMe);
              // Lukker ServerSocket
              forbindelse1.close();
              // Lukker InputStream
              inn.close();
              // flush - sender data ut p� nettet
              ut.flush();
              // Lukker OutputStream
              ut.close();
              System.out.println("File received");
              }catch(IOException e) {System.out.println("En feil har skjedd: " + e.getMessage());}
              finally {
                   try {
                   if (forbindelse1 != null) forbindelse1.close();
                   }catch(IOException e) {}
    }catch(IOException e) {
    System.err.println(e);
    }

    Hi!!
    The problem is at this line:
    System.out.println("Copies "+fileIn.read(buffer)+" bytes");
    Just comment out this line of code and see the difference. This line of code causes another "read" statement to be executed, but you are writing only the data read from the first read statement which causes approximately half the file to be send to the server.

  • User to User file transfer via FMS or RED5 in AIR application.

    Hello!
    It is possible to make file transfer from air application via server?
    I think need to create like byte array streaming or somethink like this from sender and write the destination file on receiver user pc.
    Someone know how to do this? It is possible?
    Thanks.

    Search more on socket class you can send anything between two machines using them
    see the code snippet below:
        sc = new Socket("<IP address>",8000);
      sc.connect("<IP address>",8000);
      sc.addEventListener(ProgressEvent.SOCKET_DATA, readFromServer);
      sc.writeUTFBytes("Hi this will be sent to the IP address provided by you on port no 8000!\n");
      sc.flush();

  • Problem with file transfer via Bluetooth

    I have been trying to receive some large files (43Mb) via bluetooth from another device but always get transfer fail message. But i could receive smaller flies...
    -Does this have anything to do with the device memory limit of 15MB?
    -How can i receive larger video files from other devices using bluetooth?
    -Does the BOLD have the same problem?
    Please help.
    Thanks

    What type of errors is being generated? Are you trying to save that file on device memory or media card? try moving that file on media card.
    tanzim                                                                                  
    If your query is resolved then please click on “Accept as Solution”
    Click on the LIKE on the bottom right if the post deserves credit

  • Toshiba AT300-101 file transfer via Bluetooth

    I am trying to transfer files from my AT300-101 tablet to my PC via Bluetooth but have been unable to.
    I have managed to pair and connect it
    on another note anyone know when the TOSHIBA AT300 Stand Case might be available to buy.
    Thanks

    >on another note anyone know when the TOSHIBA AT300 Stand Case might be available to buy.
    I googled around and already found one online shop who provides the TOSHIBA AT300 Stand Case
    >I am trying to transfer files from my AT300-101 tablet to my PC via Bluetooth but have been unable to.
    Did you try the Android App called: "Bluetooth File Transfer
    This allows you to send the files via Bluetooth directly to another smartphone or tabled without transferring this files to PC firstly.

  • Problem with file transfer via wi-fi!

    Hi, folks,
    Please, could someone help me to get a music file I made using Groovemaker app?
    After finish the mix, I built a song. Then, I saved it in the "mix browser".
    In the end of the exporting process, I typed the URL address displayed in the browser (http://192.168.0.188:5555/, on Firefox, Chrome and IE), but something gone wrong and, every time I export the same song - it's my first exporting action - I got a message such "The page hasn't loaded... limit time reached".
    What's the problem with my wi-fi connection? Should I set something in my router? According to the company website (http://www.groovemaker.com/gmiphone/features/) this kind of wi-fi file transfer is easy, but not to me...
    Thanks in advance!
    Alex

    What type of errors is being generated? Are you trying to save that file on device memory or media card? try moving that file on media card.
    tanzim                                                                                  
    If your query is resolved then please click on “Accept as Solution”
    Click on the LIKE on the bottom right if the post deserves credit

  • File Transfer Via ModBus

    I am hoping to transfer data (file size between 70kB~1MB) between two remote locations. I played around with “MB Ethernet Example Master” from ModBus toolkit and was able to successfully send/receive boolean and numeric values.
    Here are 2 questions:
    For my application, is Ethernet/Modbus the best way? Another way that I thought of was emailing the file, but then again I would have to deal with the mail server…etc.
    From what I could gather, the way that a file would be sent would be to read strings from the file, parse the data into packets that won’t overflow the allowable size. On the receiving and it would reconstruct the packets, and save it to a file. Does this model sound about right?

    Modbus is not intended at all for sending files between locations.  It is intended for sending values or groups of values that are located at specific modbus registers within a device or server.  For transferring files either use FTP or look at the examples for TCP/IP file transfer.

  • Automatically accepting file transfer via Bluetooth?

    I'm often sending files from my cellphone to the Mac.
    Alas, for each file I must again click "accept" in the Bluetooth File Exchange dialog. It is especially annoying since sometimes I do not even sit in front of the computer and just want to clear my phone's memory from afar.
    Is there any way to have the files accepted to be received automatically?
    Thanks!

    What you need to do is the following:
    On your blackberry:  Browse to Media, and select, pictures (for example), now press the menu button while in pictures and select "receive using Bluetooth"  Now send a file from your mac using the bluetooth file transfer.  This will work - if it doesn't then there may be an issue with either your mac or bb.  Let me know if you need further instructions.  Good luck.

  • Disconnect from WiFi Button in Yosemite (Faster File Transfers via Airdrop)

    Hi all! Just thought I'd share a great new pro-tip I found that's pretty handy.
    Sometimes file transfers through a complex or busy network with a  (think hotel lobby or coffee shop), Airdrop file transfers can run extremely slow vs. it going from computer to computer via no network (Ad Hoc). I was determined to find a work around for disconnecting from a WiFi network without turning off Wifi.
    Anyways, Yosemite introduced a much asked for feature - The disconnect from WiFi button! Just hold down option while you select the WiFi indicator on the menu bar and click disconnect! Your WiFi will continue to be on and it simply won't connect to that network again. If you now search for other computers in AirDrop, it will find them and be a much faster computer to computer connection.

    Testing in a new User will quickly tell you if the problem is system wide or if it's your User's folder that contains the problem.
    CREATE A NEW USER
    Go to System Preferences --> Create a New User in Users & Groups Switch to the New User by logging out/in or use Fast User Switching.
    Enter your Apple ID and password.
    Test Markup in Mail using the iCloud account.
    Continue testing to see what works in the new User.
    Do you still see the issue?
        If yes, then the problem is with your base files.
        If no, then the problem is in your User's folder.
    Finder - my iMac name is - iMacs iMac. All of a sudden it become iMacs iMac (2) and latter iMacs iMac (6). What are these numbers ?
    In System Preferences > Sharing you can see name. When Finder adds a number it indicates it's seeing another drive with the same name. You can select to rename but this could also be an indication of issues at the base level.
    Do you have an external drive that could be used to clone your drive in case you need to do a clean install?

  • How do I network a 4yr old Macpro with the latest 15" Retina MBP for fast file transfer (back and forth)

    Hi
    I have recently updated my equipment and now wish to use my MBP to edit files that currently reside on my old MacPro.
    I have made a wifi connecting and also set up file sharing but both prove very slow and also - once the file is ready I cannot save it back to the orginal folder.
    Basically, I have lots of stuff on my MacPro that is too big to take across, so all I wish to use my new machine and have the option to save back to the old machine as and when needed.
    Can someone advise me on what I need to do, whether that be buy some cables to take advantage of thunderbolt, or any other good working solutions.
    many thanks
    Simon
    I am also trying to copy over the font from the library but it says i cannot because of permissions.

    If both computers have ethernet ports, that is a fast and inexpensive way to connect and transfer files. You will need an ethernet cable (cost a few $$), and you have to enable file sharing on both Macs.
    As for the specifics of file transferring without Migration Assistant it depends on what you want to move. Address Book for example has Export and Import funcitonality. Safari too can import and export bookmrks, etc. etc.

  • File transfer via flash drive locks MacBook

    Switched from a PC laptop recently to a MacBook. After the usual growing pains, still have a problem occasionally in transferring large files (folders of IT documentation and some are 300-500MB) via my Cruzer 1GB flash drive. Some transfer fine, while others lock up the machine before the transfer is complete. After recovering, can transfer the file again and it may work OK. Any ideas would be appreciated.
    MacBook   Mac OS X (10.4.7)   2GB RAM

    My friend, I believe you're right on. I may be speaking too soon but I tried my Verbatim flash drive and transferred three rather large files with no problems whatsoever. Hopefully the problem is solved. I was glad to see someone else was having the same problem. I was about to dump this MacBook. The transferring of files is important to my work and I haven't got time to fool with the problem. Thanks again.
    MacBook Mac OS X (10.4.7) 2GB RAM

  • Messages, no File transfer via Bonjour

    Everything in Messages works fine for us.
    The only thing, we can't transfer files in our own network via Bonjour. Either the file does not arrive and you see only one bubble or you can see the file name, but after starting the download you receive the message "failed".
    Via the normal Message service it works (e.g. to one iPhone).
    Any idea?

    Hi Kenneth,
    If you want to convert from IDoc to flat-file format you need to use an XSLT mapping that outputs to text format (use : <xsl:output method="text"/>).Use the plain HTTP adapter and set the protocol to HTTPS. I do not think it is possible to use the Graphical mapper in XI to convert XML to text.
    As for configuring the HTTPS settings , I suggest reading the following documentation from SAP:
    http://help.sap.com/saphelp_nw04/helpdata/en/14/ef2940cbf2195de10000000a1550b0/frameset.htm
    Regards,
    Achmed
    Message was edited by: Achmed Aboulcher

  • My file transfer via nikon transfer 2 duplicates files.?

    When transfering the files some, not all, will duplicate. Some times one duplicte, other times 3-4 times. And some times the transfer will work as shoulda and transfer the single file.

    At 22MB per picture in RAW, that would be about 55 to 60 pictures. I don't recall doing a transfer that large yet.
    However, I just tested this. I set up my camera to save the pictures in both RAW and jpeg. When I inserted the SD card in my Mac and opened iPhoto. It showed two copies of the same picture. I selected to transfer all of the pictures and now I have two sets of the same picture. One in jpeg and one in RAW.
    It maybe possible that your camera is set up to save the file in both RAW and jpeg.
    Saving in RAW takes up more disc space, but it's also better for post-production editing. If you have the software to view the RAW files, then I suggest to use RAW only on the camera. If you decide to send the picture via email or post them online. The software will automatically switch them to jpeg.
    I know that iPhoto, Aperture and Photoshop CS6 are able to read the RAW files from my camera.
    KOT

  • File Transfer via Ethernet

    Hello, I'm trying to transfer files from an antique beige G3 running OS 9.1 to an iMac running Leopard. I've got the two machines side by side and connected via Ethernet cable, and I've got File Sharing enabled (I think) on both machines. Now what?? I have a feeling from past attempts that these things have to be done in the correct order (starting up one machine, hooking up the Ethernet, starting up the other,...)
    I'd be grateful for complete step-by-step instructions!!
    Thanks, Ch.S.

    Perhaps this may help: Mac OS- How to Connect to File Sharing or Apple File Services (AFP). Be sure to enable AppleTalk on the OS X machine. You may need a crossover Ethernet cable. See Apple products that require an Ethernet crossover cable.

  • File Transfer via SFTP

    Hi All,
    Please guide to transfer the file from remote system or move file to the remote system via SFTP. I tried via FTP and its working fine. Please give the soluition also give example to achieve this in SFTP and this is very urgent.

    PavithraKarthikeyan wrote:
    Please guide to transfer the file from remote system or move file to the remote system via SFTP. I tried via FTP and its working fine. Please give the soluition also give example to achieve this in SFTP and this is very urgent.From what I understand, SFTP is simply FTP with a different connection style; so I suspect it might be as simply as telling your existing FTP software that you want to use SFTP.
    Winston

Maybe you are looking for

  • PR or Reservation?

    We have a problem related to using PR or Reservation in order to create requisition for material, due to scenario described below: Our purchasing scenario is descried below: "In our organization when a request for a good is created, there are some st

  • What will be the CoS priority for the options below?

    + voice + video interactive + video streaming + call signaling + ip routing + network management

  • GCU membership set to expire 11 months too early

    Hello! I'm posting here about an issue with my Gamer's Club Unlocked membership. These snippets of my emails to Best Buy Customer Support should explain my problem: 12/19/2013 Me: I just renewed my Best Buy GCU membership for an additional two years,

  • Uses of REUSE_ALV_EVENTS_GET

    In some report program after preparing field-catalog i've seen the use of REUSE_ALV_EVENTS_GET. But i think for report display, field catalog preparation and alv display function module call is enough to get the output. So what's the specific purpose

  • BW on HANA - Unclear points

    Hi, We have ECC (version 6) & BW (Version 7.3) system. We load data from ECC to BW at regular intervals. We have 200+ WEBI reports over cubes in SAP BW. There are lot of areas like SCM, Payroll, Project system where the loads are taking lot of time.