File Transfer (Missing start of file)

Hi there, I'm undertaking part of a software project at University and struggling to fix a piece of code myself and a friend have wrote after exhausing most of the good java programmers in our department.
We're simply trying to send files over a network via TCP, the main problem we're encountering is that if we send say a text file, a varying number of characters will appear missing. Normally we'll recieve between 300-400 of the 500 bytes we send for example, and these characters are always missing from the start of the file. Obviously this is the bit we need to fix, at the end we're aiming to be able to send media files (jpg, gif, txt, wav, avi) and hopefully objects aswell.
The way its intended to work at present is that the server sends file information to the client (filename and filesize), and then the client listens, and writes the same number of bytes as the filesize to the new file it creates (though I'm sure you'll work that out in seconds). The file has been read in, and wrote back on the server side just to ensure the reading/sending section was working which it was.
Server Side:
FileServer.java: import java.io.*;
import java.net.*;
public class FileServer
   private ServerSocket serverSocket = null;
   private Socket socket = null;     
   public String fileDir = "H:/JAVA/";
   public String fileName = "text.txt";
   public String filePath = fileDir + fileName;
   public PrintWriter log;
   public BufferedReader in;
   public PrintStream out;
   public FileServer() throws IOException
      try {
              serverSocket = new ServerSocket(1138);
              System.out.println("Server initialised and listening on port : 1138.");
      catch (IOException e){
         System.out.println("Could not listen on port : 1138");
      try {
         socket = serverSocket.accept();
         System.out.println("Client" + serverSocket.getInetAddress() + "connected.");
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         out = new PrintStream(socket.getOutputStream(), true);
      catch (IOException e){
         System.out.println("Could not accept client.");
         System.exit(1);
     boolean done = false;
     while (!done)
        try{
           String line = in.readLine();               
           if (line == null)
              done = true;
          else
               if (!line.trim().equals("CLOSE"))               
                   if (line.trim().equals("SEND FILE"))
                       sendFile(filePath, socket);
               else
                   done = true;                         
            catch (IOException e) {
               System.out.println("Cannot read data from client");
               System.exit(1);
      socket.close();
public void sendFile( String filename, Socket socket )
   File file;     
   try{
         file= new File(filePath);
         int c =0;
         FileInputStream fis = new FileInputStream(file);
         out.println(fileName+":"+file.length());
         OutputStream os = socket.getOutputStream();
         int i = 0;
         while((c = fis.read()) != -1)
             i++;
            System.out.println(i +"  "+ c);
            os.write(c);
         System.out.println("File "+filePath+" sent:"+file.length());
         fis.close();
   catch( Exception e ) {
        System.out.println("sending file error");
        e.printStackTrace();
        System.exit(1);
public static void main (String [] args) throws IOException
   FileServer myFileServer = new FileServer();
Client Side:
Client.java: import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class Client
  private Socket clientSocket = null;
  public String filePath = "H:/java/Temp";
  PrintWriter out = null;
  BufferedReader in = null;
  String host = "144.32.152.154";
  int port = 1138;
  Integer fileSize;
  String filename;
  public Client() throws IOException {
    InputStream inputStream;
    try {
      clientSocket = new Socket(host, port);
    catch (IOException e) {
      System.out.println("Could not create connection");
      System.exit(1);
    out = new PrintWriter(clientSocket.getOutputStream(), true);
    inputStream = clientSocket.getInputStream();
    in = new BufferedReader(new InputStreamReader(inputStream));
    out.println("SEND FILE");
   String details;
   while((details = in.readLine()) != null)     
      System.out.println(details);
      StringTokenizer sToken = new StringTokenizer(details, ":");
      filename = sToken.nextToken();
      fileSize = Integer.valueOf((sToken.nextToken()));
      System.out.println(filename);
      System.out.println(fileSize);
      FileOutputStream file = new FileOutputStream(new File(filePath,filename));
         for (long i=0; i<fileSize.longValue(); i++)
            int c = inputStream.read();
            file.write(c);
            System.out.println(i);
            System.out.println(fileSize);
        System.out.println("Exited Loop");
        file.flush();
        file.close();
        clientSocket.close();
        System.out.println("The End");
        System.exit(-1);
  public static void main(String[] args) throws IOException
    Client myClient = new Client();
} I'd appreciate any help you can offer to fix the problem! Thanks
Ian Wright

OK. There were some mistakes in the code. Some made by me, some by you.
First of all: The byte array which acts as a buffer for reading the file content from the socket cannot have the size of the whole file. Normally it is suggested to set to 8-32kB.
Second thing: I was too fast in giving you the idea of reading the details only once to an array. Sometimes the Client program is faster than the FileServer and although the array has space for "nameLength" bytes it reads a lot less. That way the details aren't recieved properly. To solve this I've added a loop that waits for the inputStream to retrieve enought data.
Last but not least: I've been told that it is not wise to close the socket at the server side. If you close the socket the OutputStream is cut off without a warning. Close the OutputStream instead.
I remember that you asked me to reply via e-mail but I think that posting the solution here will be more usfull to others. Here's the code:
Client3.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client3
  private Socket clientSocket = null;
  OutputStream out;
  public String filePath = "E:/";
  String host = "127.0.0.1";
  int port = 1138;
  Integer fileSize;
  String filename;
  static final byte SEND = 1;
  static final byte DONE = 2;
  static final byte ERROR = 0;
  public Client3()throws IOException{
    DataInputStream inputStream;
    System.out.println("Hello");
    try {
      clientSocket = new Socket(host, port);
    catch (IOException e) {
      System.out.println("Could not create connection");
      System.exit(1);
    out = clientSocket.getOutputStream();
    inputStream = new DataInputStream(clientSocket.getInputStream());
    out.write(SEND);
     byte nameLength = (byte)inputStream.read();
     byte[] nameArray = new byte[nameLength];
     while (inputStream.available()<nameLength) // we have to wait for the details to arrive :]
          try {
               Thread.sleep(10);
          } catch (InterruptedException e) {
               System.out.println("Client impatient ... couldn't wait");
          inputStream.read(nameArray);
     String details = new String(nameArray);
     StringTokenizer sToken = new StringTokenizer(details, ":");
    filename = sToken.nextToken();
    fileSize = Integer.valueOf((sToken.nextToken()));
     System.out.println(filename+":"+fileSize);
      FileOutputStream file = new FileOutputStream(new File(filePath,filename));
               while (true) { // now read the file one piece after a nother :P
                    byte[] fileBuffer = new byte[8*1024];
                    int cnt = 0;
                    cnt = inputStream.read(fileBuffer);
                    if (cnt==-1) break;
                    file.write(fileBuffer,0,cnt);
      file.flush();
      file.close();
      out.close(); // T100 would say: Hasta la vista ... baby!
      System.out.println("The End");
      System.exit(-1);
  public static void main(String[] args) throws IOException{
       Client3 client = new Client3();
FileServer3.java
import java.io.*;
import java.net.*;
public class FileServer3 {
   private ServerSocket serverSocket = null;
   private Socket socket = null;     
   public String fileDir = "";
   public String fileName = "image.bmp";
   public String filePath = fileDir + fileName;
   public PrintWriter log;
   public InputStream in;
   public DataOutputStream out;
   static final byte SEND = 1;
   static final byte DONE = 2;
   static final byte ERROR = 0;
   public FileServer3() throws IOException
      try {
              serverSocket = new ServerSocket(1138);
              System.out.println("Server initialised and listening on port : 1138.");
      catch (IOException e){
         System.out.println("Could not listen on port : 1138");
    while(true){
      try {
         socket = serverSocket.accept();
         System.out.println("Client" + serverSocket.getInetAddress() + "connected.");
         in = socket.getInputStream();
         out = new DataOutputStream(socket.getOutputStream());
      catch (IOException e){
         System.out.println("Could not accept client.");
         System.exit(1);
      try{
           byte b =(byte)in.read();
          if (b == SEND)               
                       sendFile(filePath, out);
       catch (IOException e) {
               System.out.println("Cannot read data from client");
               System.exit(1);
public void sendFile( String filePath, DataOutputStream out ) {
     File file;
   try{
     file = new File(filePath);
         FileInputStream fis = new FileInputStream(file);
     String details = fileName+":"+Long.toString(file.length());
     System.out.println((byte)details.length()+": "+details);
     out.write((byte)details.length());
     out.writeBytes(details);
     System.out.println("File details sent");
     while (true) { // Momma always said to bite before swallowing :D
          byte[] byteArray = new byte[8*1024];
          int cnt = fis.read(byteArray);
          if (cnt == -1) break;
          out.write(byteArray,0,cnt);
         System.out.println("File "+filePath+" sent:"+file.length());
         out.close(); // Say goodbye and the door will close by it self %)
   catch( Exception e ) {
        System.out.println("sending file error");
        e.printStackTrace();
        System.exit(1);
  public static void main (String [] args) throws IOException {
     FileServer3 myFileServer = new FileServer3();
}I hope this will help you out. If there are any other errors that I've missed than point them out to me and I'll se what can be done later. I have a cake in the oven and don't have enough time right now :].
...:: byElwiZ ::...

Similar Messages

  • Is there any way to use a file transfer protocol to upload files to icloud?

    Is there any way to use a file transfer protocol to upload files to icloud?

    Unfortunately, no.
    You will need a 3rd party web host to upload your websites to. Depending on the version of iWeb you are using you have a couple of publishing options:
    iWeb ’09 (3.0.4) you can publish to an FTP Server or a local folder. ( With the built in FTP in iWeb you will end up with an address like “www.YourDomain.com/sitename/Home.html )
    iWeb ’08 you can publish your website to a local folder
    Basically all Web Hosting companies are iWeb-compatible.
    If you’re looking for a good hosting I would recommend IX Web Hosting I have been using them to host my own websites for several years now and that their customer support is awesome too.
    http://jeffnitschke.com/IXWebHosting.html
    http://jeffnitschke.com/wordpress/2012/06/how-do-i-move-my-mobileme-site-ix-web- hosting-blog/
    "I may receive some form of compensation from my recommendation or link."

  • Missing Start Database file/folder

    Hi,
    I'm on a Windows 98 platform. When loading Oracle 8i Lite from cd secured on Trial License, 'Start Database' file/folder does not load. As a result, I can not open SQL Plus to access database (TNS destination error).
    In as much as Win 98 does not have a 'Controls' folder in Control Panel, have not been able to workaround as might in NT.
    Thanks in advance for your help
    Charley
    ([email protected]

    Hi,
    I'm on a Windows 98 platform. When loading Oracle 8i Lite from cd secured on Trial License, 'Start Database' file/folder does not load. As a result, I can not open SQL Plus to access database (TNS destination error).
    In as much as Win 98 does not have a 'Controls' folder in Control Panel, have not been able to workaround as might in NT.
    Thanks in advance for your help
    Charley
    ([email protected]

  • JME Socket File Transfer - Problem with writing file

    Hi everybody, i'm trying to code a P2P app for a school project and i have a problem when trying to write to a file.
    This method recieves a file form a Socket Server computer that tries to send me a file to the mobile client.
    The method recieves the IP adress (String add) and the port of the server.
    Also, i would like to know about the buffer(byte) size.
    This codes runs well in emulation, but it doesn`t write to a file.
    And the main problem is:
    "When i run this in the mobile, the file is created in the cellphone memory with a size of 0kb."
    The server code was tested with a computer client and recieved the file succesfully.
    The server recieves de socket connection form the cellphone without problem.
    public void recibirArch(String add, int port) throws Exception {
    try
    recibArch.setText("Espere por favor...");
    long start = System.currentTimeMillis();
    int bytesRead;
    int pasos = 12;
    int current =0;
    SocketConnection sock = (SocketConnection)Connector.open("socket://"+add+":"+port);
    byte [] mybytearray = new byte [1024];
    InputStream is = sock.openInputStream();
    FileConnection fc = (FileConnection) Connector.open("file:///"+saveRoot+"5letras.txt",Connector.READ_WRITE );
    if( !fc.exists() ){
    fc.create();
    } else
    fc.truncate(0);
    DataOutputStream fos = new DataOutputStream(sock.openOutputStream());
    bytesRead = is.read(mybytearray,0,mybytearray.length);
    current = bytesRead;
    while ((current = is.read(mybytearray)) != -1)
    fos.write(mybytearray, 0, current);
    fos.flush();
    current+=bytesRead;
    long end = System.currentTimeMillis();
    fos.close();
    sock.close()
    catch(Exception err)
    String error = "ERROR: " + err.toString() + "\nDescripción: "+ err.getMessage();
    System.out.println(error);
    txtLog.setString(error);
    Edited by: xtylo on Sep 30, 2008 10:56 AM

    Thank you Tunde for looking at my issues!
    The file size is not an issue here. We tested with empty files or files with smaller than 1KB sizes. They all showed problem. The frequency of file transfer shouldn't be a problem either. Through some user interaction on front panel, a couple of files will be transferred. That's basically how often the file transfer occurs.
    Interestingly enough, I replaced the copy.vi with a subvi I created using DOS command with System Exec.vi and the issue of copying files went away. My co-worker tested on both XP machine and Windows 7 machine. The DOS command worked fine thru Lavview's System Exec.vi. I think I can take that as a work-around if we can't figured out why copy.vi wouldn't work. Still, it would be nice to know why it doesn't work.
    Now I'm still facing some issues with the usage of Check If File or Folder exist.vi. Sometimes it can detect the existing files and sometimes it doesn't.
    Thanks very much! 

  • When I save file: media missing in motion file

    when I save file: media missing in motion file

    Dear Mr Khalid,
    I modified the VI again by using the General Error Handler, by placing it after the Read from Binary File. The Simple Error Handler will be as is. When I build and ran the application the Error 4 do not show up anymore.
    Attachments:
    saving new data.GIF ‏61 KB

  • When the webhelp folder is hosted, an error message is displayed, "whproxy.js file is missing", though the file exists in the folder.

    I have recently updated my project file with DUCC concept using the trial version of Robohelp 10. After generating the project, I have submitted the webhelp for hosting. When the concerned person tried to host the webhelp folder to the server, it is indicating that the whproxy.js file is missing, though it exists in the hosted webhelp folder.
    Please help me out with this.

    Does the help work when you open it locally? If it does, something is wrong with the upload progress or the server configuration. If it doesn't, try generating your output again.
    Kind regards,
    Willam

  • My ipad 2 is a few months old now and has just had its first glitch, it will sync ok as long as I have no photo sync selected, as soon as I select to sync any photos off my imac it mentions that no sync is possible because a file is missing? What file?

    ipad 2, it says version 4.3.5, has just had its first glitch. It will not sync iphoto but everything else sync's ok.  I did restore to factory settings because it came up with (error -50) now it mentions a file is missing, but no longer mentions (error -50). This is the first problem I have had.

    If the cache isn't the issue, click 50 on this page >  iOS: Resolving update and restore alert messages
    Powering Apple and third party peripherals through USB

  • How to spool file to where start script file located

    I'm writing a sqlplus script, eg. runMe.sql, which is going to run in customer env, will generate some data files eg. result.csv.
    By specify location such as 'spool /certain/path/on/disk/result.csv', I can spool to any path I want. However, my concern is  below:
    1. We gets many customers and the script might be run under different location.
    2. I don't know where customer would save the script, furthermore, I don't want customer to input location manually every time.
    3. Generally, customer would run the script something like "sqlplus username/password@sid @/certain/path/on/disk/runMe.sql". They don't want to pass any parameter at run time.
    4. I wanna spool file to "/certain/path/on/disk" automatically, as a result, result.csv file would appear under same path with runMe.sql.
    5. I tried "spool ./result.csv" but it navigate to where sqlplus session is running.
    6. Also tried &0 etc, but make no sense.
    Can anyone tell me how to obtain start running script file path in sqlplus script(runMe.sql) ? Just like access command parameters under Linux.
    $0 is the name of the command
    $1 first parameter
    $2 second parameter
    $3 third parameter etc. etc
    $# total number of parameters
    $@ all the parameters will be listed
    Thanks in advance.

    Are you looking for SQLPATH ?
    A good and clear example by Paul @ https://forums.oracle.com/message/3727891
    In this way your customer has to set one environment variable SQLPATH=/location/of/script/file/where/they/put/your/runMe.sql and just say :
    spool %sqlpath%\result.csv
    in your runMe.sql.  So, runMe.sql and result.csv will be on SQLPATH location.
    Regards
    Girish Sharma

  • File transfer Gmail HELP! FILES WONT GO THROUGH!

    My friend and I just started using iChat and we both use google talk. She is still using Snow Leopard and I'm using Lions.
    For some reason she can send files through google talk and I can recieve them, but I can't send files back.
    Is this because of the OS difference or is it just something wrong with google talk?
    HELP I WANT TO BE ABLE TO SEND FILES!

    https://www.google.com/search?sourceid=chrome-psyapi2&rlz=1C1CHFX_enUS546US546&ion=1&espv= 2&ie=UTF-8&q=adobe%20customer%…
    This is a Photoshop User forum if you have a problem with Adobe you should deal with Adobe. 1 (800) 833-6687 Adobe Systems, Customer service.
    Users here do not work for Adobe.

  • File transfer Open dataset CSV file Problem

    Hi Experts,
    I have an issue in transferring Korean characters to a .CSV file using open dataset.
    data : c_file(200) TYPE c value '
    INTERFACES\In\test8.CSV'.
    I have tried
    open dataset  c_file for output LEGACY TEXT MODE CODE PAGE '4103'.
    open dataset  c_file for output    in TEXT MODE ENCODING NON-UNICODE.
    open dataset  c_file for output    in TEXT MODE ENCODING Default.
    Nothing is working.
    But to download to the presentation server the below code is working. How can the same be achieved for uploading the file to application server.
    CALL METHOD cl_gui_frontend_services=>gui_download
          EXPORTING
            filename                = 'D:/test123.xls'
            filetype                = 'ASC'
            write_field_separator   = 'X'
            dat_mode                = 'X'
            codepage                = '4103'
            write_bom               = 'X'
          CHANGING
            data_tab                = t_tab
          EXCEPTIONS
            file_write_error        = 1
            no_batch                = 2
            gui_refuse_filetransfer = 3
            invalid_type            = 4
            no_authority            = 5
            unknown_error           = 6
            header_not_allowed      = 7
            separator_not_allowed   = 8
            filesize_not_allowed    = 9
            header_too_long         = 10
            dp_error_create         = 11
            dp_error_send           = 12
            dp_error_write          = 13
            unknown_dp_error        = 14
            access_denied           = 15
            dp_out_of_memory        = 16
            disk_full               = 17
            dp_timeout              = 18
            file_not_found          = 19
            dataprovider_exception  = 20
            control_flush_error     = 21
            not_supported_by_gui    = 22
            error_no_gui            = 23
            OTHERS                  = 24.

    Hi,
    I would recommend to use OPEN DATASET ... ENCODING UTF-8 ...
    If your excel version is unable to open this format, you can convert from 4110 to 4103 with report RSCP_CONVERT_FILE.
    Please also have a look at
    File upload: Special character
    Best regards,
    Nils Buerckel

  • File Information missing from NEF file

    When loading a NEF file, I cannot get any information from Camera Data 1 or 2. Normally you would get ISO, apeture etc. I am using Elements V4.0 with Photoshop Camera Plug-in V3.6.0.147. When looking at other JPG files all this information is available.
    Thank you

    OP simply refers to the "original poster". I was able to extract that NEF files from the DNG file and then run it through the DNG converter again. Without the NEF file embedded, the DNG file size was 8.66 MB. There is a change preferences button near the bottom of the DNG converter screen. You need to go into the preferences and make sure to deselect the indicated option.

  • Proxy to File transfer using the GZIP file transfer

    Hi Sdn,
    I have requirement where I need to convert the file to GZIP extension and keep it at Application layer.
    Can any one please help me how to convet the file to GZIP in file adaptor?
    Thanks
    Naresh N

    I think this option is for the normal ZIP.
    Honestly I was afraid this could be true.
    So I think there is no other option than to create your own adapter module. Find a step-by-step guide on how to create adapter modules here:
    http://wiki.sdn.sap.com/wiki/display/NWTech/CustomAdapterModuleDevelopment-SAPPI+7.1
    And a Java class that will help you compress the data stream with GZIP:
    http://docs.oracle.com/javase/1.5.0/docs/api/java/util/zip/GZIPOutputStream.html
    Hope this helps,
    Greg

  • File Transfer (stalling on receiving files)

    When I receive files IChat will stall out (IChat 3.1.1). Most recent was someone on my same network and the file was 16mb. If we repeat the process if will eventially work. I have sent the same person files that are 200mb and up with no problems.
    Anyone have any ideas on what causes this?
    thanks,
    Jamie

    Changed the server port to 443 . . forgot about that one!

  • Missing Horizontal Photo Files - Thumbnails visible

    I was going back through my iPhoto Library and came across a strange issue. It appears that a vast majority of my horizontal photo files are missing starting in July of this year and going back to 2005. The thumbnails show up but when I doubleclick I get the dreaded exclamation point. When I search for the file, it is not on the harddrive. Fortunately I have a backup from August that appears to have the pictures in it, I started using a Time Capsule in September and it only has the corrupt library on it.
    1. How do I get these pictures back, where did they go?
    2. How do I restore from the backup harddrive? I cannot go through thousands of pictures, write down the file name and restore them one by one?
    3. Doesn't this seem odd that the files for the vertically aligned photos are OK?
    4. This is extremely disconcerting, ie what else is missing?

    sareddie
    Your files should be perfectly safe...
    iPhoto (like iTunes) is a database but unlike most databases which hide the data away from the file system, it stores the data in plain sight. So rebuilding works on the files that track the pictures, rather than on the pictures themselves.
    Here's how the iPhoto Library Folder is structured: In this folder there are various files, which are the Library itself and some ancillary files. Then you have three folders
    Originals are the photos as they were downloaded from your camera or scanner.
    (ii) Modified contains edited pics, shots that you have cropped, rotated or changed in any way.
    This allows the Photos -> Revert to Original command - very useful if you don't like the changes you've made.
    (iii) Data holds the thumbnails the the app needs to show you the photos in the iPhoto Window.
    So that explains why the Modified Version of a pic is present, but begs a question... where have your missing pics gone? And how did they get there?
    Rebuilding a database would try to recreate the link between the thumbnail in the iPhoto Window and the file, but if the file is missing, it obviously cannot do it.
    Is there any possibility that you - or another user - might had accidently deleted or moved these files? Are they in your trash? If you have a file name try Spotlight for them.
    Regards
    TD

  • IChat have file transfer manager?

    Does iChat in Leopard AND Tiger have a file transfer manager in case file transfer gets interrupted? Thanks

    Legaleye30000 wrote:
    Well this is what I'm trying to do:
    -If something happens and disconnects and we later come back to our computers and see that it failed, can we resume from where the file got disconnected instead of starting all over again?
    I do believe this is possible. As long as you don't move the file or anything like that, it should continue where it left off. The person sending the file has to send it again, and the person on the other end must accept it. It won't start automatically (unless you somehow tell iChat to auto accept files).

Maybe you are looking for