Trouble sending files over the network.

I have a network application that corrupts any files that it sends, although the received file is very close (but never exact) to the number of bytes it should be. There is a socket client that each client has, and the Packet data structure is searializable and simply contains a string message and the byte[]. Am I doing something wrong?
Here is my code for Sending:
ObjectOutputStream toOtherClient = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream fromOtherClient = new ObjectInputStream(client.getInputStream());
Packet fileRequest = (Packet)fromOtherClient.readObject();
File file = new File(DefaultConfig.defaultFileDirectory+"\\"+fileRequest.getMessage());
FileInputStream fromDisk = new FileInputStream(file);
BufferedInputStream fromDiskBuffered = new BufferedInputStream(fromDisk);
byte[] buffer = new byte[maxPayload];
while(fromDiskBuffered.available() > 0)
     if (fromDisk.available() > maxPayload)
          fromDiskBuffered.read(buffer);
          toOtherClient.writeObject(new Packet(Packet.Command.File,"",buffer));
     else
          buffer = new byte[fromDiskBuffered.available()];
          fromDiskBuffered.read(buffer);
          toOtherClient.writeObject(new Packet(Packet.Command.File,"",buffer));
fromDiskBuffered.close();
fromDisk.close();
toOtherClient.writeObject(new Packet(Packet.Command.File,"ack"));
fromOtherClient.close();
toOtherClient.close();
client.close();Here is my code for recieving:
Socket client = new Socket(host, Integer.parseInt(port));
ObjectOutputStream toOtherClient = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream fromOtherClient = new ObjectInputStream(client.getInputStream());
FileOutputStream toDisk = new FileOutputStream(DefaultConfig.defaultFileDirectory+"//"+whatFile); BufferedOutputStream toDiskBuffered = new BufferedOutputStream(toDisk);
toOtherClient.writeObject(new Packet(Packet.Command.File,whatFile));
Packet incoming;
while(true)
     incoming = (Packet)fromOtherClient.readObject();
     if (incoming.getMessage().equals("ack"))
          break;
     byte[] fileData = (byte[])incoming.getData();
     toDiskBuffered.write(fileData);
toDiskBuffered.flush();
toDiskBuffered.close();
toDisk.close();
fromOtherClient.close();
toOtherClient.close();
client.close();

You're assuming that available() gives you the total length of the file, which it doesn't, and you're ignoring the result returned by the read call, so you're assuming you've read data you may not have read.
I would rethink the tactic of reading the entire file into a single buffer - this doesn't scale. It's only safe if you know that the file size has an upper bound and that this is relatively low.

Similar Messages

  • I need to copy files over the network PSSession . ( Firewall / DMZ / Etc. )

    Hello
    I need to copy files over the network PSSession . ( Firewall / DMZ / Etc. )
    I have a script where I copy from my local server ( server1) to the remote server ( server2 ), but I can´t not make script that will copy from the remote server to my local by my session. From server2 to server1
    Script is as below ...:-)
    HELP : ....
    winrm s winrm/config/client '@{TrustedHosts="SERVER2"}'
        $Source = "D:\test\ok.log"
        $Destination = "D:\test\ok.log"
        $session = New-PSSession -ComputerName SERVER2
    Set-StrictMode -Version Latest
    ## Get the source file, and then get its content
    $sourcePath = (Resolve-Path $source).Path
    $sourceBytes = [IO.File]::ReadAllBytes($sourcePath)
    $streamChunks = @()
    ## Now break it into chunks to stream
    Write-Progress -Activity "Sending $Source" -Status "Preparing file"
    $streamSize = 1MB
    for($position = 0; $position -lt $sourceBytes.Length;
        $position += $streamSize)
        $remaining = $sourceBytes.Length - $position
        $remaining = [Math]::Min($remaining, $streamSize)
        $nextChunk = New-Object byte[] $remaining
        [Array]::Copy($sourcebytes, $position, $nextChunk, 0, $remaining)
        $streamChunks += ,$nextChunk
    $remoteScript = {
        param($destination, $length)
        ## Convert the destination path to a full filesytem path (to support
        ## relative paths)
        $Destination = $executionContext.SessionState.`
            Path.GetUnresolvedProviderPathFromPSPath($Destination)
        ## Create a new array to hold the file content
        $destBytes = New-Object byte[] $length
        $position = 0
        ## Go through the input, and fill in the new array of file content
        foreach($chunk in $input)
            Write-Progress -Activity "Writing $Destination" `
                -Status "Sending file" `
                -PercentComplete ($position / $length * 100)
            [GC]::Collect()
            [Array]::Copy($chunk, 0, $destBytes, $position, $chunk.Length)
            $position += $chunk.Length
        ## Write the content to the new file
        [IO.File]::WriteAllBytes($destination, $destBytes)
        ## Show the result
        Get-Item $destination
        [GC]::Collect()
    ## Stream the chunks into the remote script
    $streamChunks | Invoke-Command -Session $session $remoteScript `
        -ArgumentList $destination,$sourceBytes.Length
        Remove-PSSession -Session $session

    But have will the script look,  if i need to copy from
    From server2 to server1.
    My script copy from server1 to server2 and working, but I need server2
    to server1.

  • Streaming audio file over the network w JMF. How to know when the file end

    Hi
    I am streaming audio file over the network using JMF. I want to be able to know when a file end so I can close the streaming session.
    Can some one please help
    Thanks

    If you put a ControllerListener on the Processor that's associated with generating the RTP stream, it'll generate an "EndOfMedia" event when the end of the file is reached.

  • Corporate Win7/Office 2010 | Severe Lag when opening Office 2010 files over the network

    Good Evening Everyone,
    I work in a corporate environment for one of the top banks in the country (USA). We recently upgraded our computers to Windows 7. (The image has office 2010 included in the build)
    I've been experiencing some severe lag when opening Office files over the network. Let me start by saying I've researched a lot and have yet to find a solution that works or even makes much of an improvement. 
    Notes: My laptop is new (64-bit Win 7 Enterprise). The remote desktop where the files lie is new as well. (64-bit Win 7 Enterprise) Both computers have good hardware and more than enough juice to handle applications. 
    There are certain files I work on along with other co-workers that we store on a computer within the office. We simply create shortcuts to the files on our local machines and make changes, etc. from there. However, after this upgrade, every time I try to
    open a file on the remote computer, it takes over a 1 minute to load. I've spoken to our support team who sent someone out and confirmed it's not the network. 
    Both computers are on the same subnet as well. I've changed the trust center settings on both the client computers and "server" to trust any computer on the network. I have also changed the network card's speed from "Auto Negotiate" to
    full duplex 100mbps with no luck.
    I am out of options here and in desperate need for a fix. Even saving changes to a file we work on takes forever. 50% of the time when I close a spreadsheet, the title bar has a not responding message and takes a minute to eventually close. 
    PS: Extra Info : All computers run McAfee AV and use McAfee for disk encryption. I've confirmed all computers are up-to-date in every respect with the AV software. 
    Thanks,

    Try: 
    Open My Computer.
    Open the Tools menu and choose Folder Options...
    Select the File Types tab.
    Select the extension (for example DOC, or XLS) of the file that is slow to open.
    In the Details section, click [Advanced], and another dialog box will open. 
    In the Actions section, click Open then click [Edit...], and another dialog box will open.
    http://windowssecrets.com/forums/showthread.php/149672-10-9-2012-Updates-and-very-slow-opening-of-Office-files
    KR

  • WIFI dies when transferring big files over the network

    Hi, I have Dell Inspiron 1520 with ipw3945 driver, when I transfer big files over the network, my wifi dies, anybody knows what could it be? If you need additional information, feel free to ask...
    Thanks in advance

    I guess we shall see. I can't imagine we are the only 7 with these issues.  Mine is mainly just lag... and overall slowness.  I hope to work through this.  If it lasts much longer I will have to revert back all 3 of my lappies to FC which I really do not want to do.  But on the lappies i connect via wireless 90% of the time and need it to work. 
    By the way how are you guys configuring your wifi?  I am using the iwl drivers and wicd.
    Well I did some more testing and loaded up netcfg and still get the same results so that rules out that part.  I also did some packet captures and I am getting a bunch of tcp retransmissions followed by tcp segment lost followed by a reset which in turn kills my rdp session (remote desktop protocol). I also went back several versions of the uucode driver and still get the same reults so I guess it seems to be a kernel issue.  Back to FC I go.  Damn shame...
    Last edited by BKJ (2008-10-08 01:08:56)

  • Bluetooth mouse cuts out when transferring files over the network

    Just as the title says: whenever I copy files to a PC over the network (via SMB I think its called) My bluetooth mighty mouse will start getting very jerky and makes is very difficult to move the cursor on the screen. However, my Bluetooth keyboard is comply fine. Both are using Lithium batteries and where just replaced about a month ago. Also, both are in close range...about 2 feet. And it only happens when coping files.
    Any ideas?
    -Scott

    I don't connect to network volumes that often, but I did again today and noticed that my bluetooth keyboard completely cut out (had the "discounted" HUD come up) and then the keyboard would not reconnect until the file copy was complete. I don't know about the mouse as lately I've been using my Microsoft mouse that hasn't been giving me any troubles. (like really, Microsoft and "no troubles" in the same sentence??? lol)

  • Weird X on corner of copied file over the network

    i was copying a file from my Mac Pro (Lion) to my MBP (ML) over the network and i noticed this little x in a black box on the top left hand corner of the icon while it was being copied.
    does anyone know if this is normal?
    the two little red marks mean that the file is a windows file for my virtual machine but i have seen this x before and i was curious to know if this is in fact a Mac OS functionality.
    TIA

    OK. weird. the files on my dropbox have this weird blue x and then a green checkmark in this spot if i am not mistaken.
    so we are saying this is a function of a PROGRESS BAR and it goes away when the copy has completed?
    i mean, it did go away over here but i don't remember seeing it before for some reason.
    THANKS

  • Send BufferedImage over the network

    I have already successfully setup a client/server connection. The issue, is when I send the BufferedImage over the network, it says:
    "Caused by: java.io.NotSerializableException: java.awt.image.BufferedImage"
    Can someone please tell me how to fix this?

    Like the exception say, BufferedImage is not serializable. You cannot serialize it. The problem will go away if you don't try to serialize it. Of course, that doesn't answer the question you really meant to ask... which I'll leave for somebody else.

  • I cannot printany web pages or emails over a wireless home network. My OS is windows 7 and am using an Epson printer. I know I have the home network set up correctly as i can print files over the network.

    I cannot print any email or web pages over a wireless home network. I know that I can print my files over this network, just not anything from the web or emails using Firefox. I am using Windows 7 and printing to an Epson.
    == This happened ==
    Every time Firefox opened
    == when I set up the wireless home network.

    The most likely reason for this is that the wrong printer is chosen in the File->Print window.
    In Firefox, go to File->Print and click the dropdown box with printer names. Ensure that the correct network printer is selected, then try printing again.

  • Slow access when opening XLS or DOC files over the network but XLSX and DOCX files are fast

    I am working with a small office that has 3 Windows 7 Pro PC's.  Two of these PC's have shared folders that hold Word and Excel files and all 3 of the PC's have drives mapped to these shared folders.  When browsing these mapped drive in Windows
    Explorer  and double-clicking a file 1 of the computers takes about 30-50 seconds to open any file with a .doc or .xls extension.  It opens .docx and .xlsx files in a couple seconds though, it also open PDF files very quickly.  The other 2 PC's
    have no trouble any any type of file.  I have tried many things over the last couple weeks to get this fixed.  I have added the file locations as 'trusted locations' in the Trust Center and added a couple Registry tweaks to the SMB/ lanman workstation
    and server. 2 PC's are running Office Pro 2010 SP2 and the other is Office Pro 2013, the one having the slow access is running Office 2010.  Has anyone come across this problem and have any advice??

    Try: 
    Open My Computer.
    Open the Tools menu and choose Folder Options...
    Select the File Types tab.
    Select the extension (for example DOC, or XLS) of the file that is slow to open.
    In the Details section, click [Advanced], and another dialog box will open. 
    In the Actions section, click Open then click [Edit...], and another dialog box will open.
    http://windowssecrets.com/forums/showthread.php/149672-10-9-2012-Updates-and-very-slow-opening-of-Office-files
    KR

  • Accessing a file over the network

    Hi ,
    I need to access a file for read/write operations. The file may exist or may not on another computer in my network. I use the File class for accessing the file. (File f = new File("\\192.23.23.23\file.txt");
    My problem is how can I know if I cannot access the file because I have network issues (e.g. The file exists but the network is down so its not accessible) or because the file really dont exist on the given address.
    Since File operations does not throw a specific exception Its hard to know the exact reason for access failure.
    Any suggestions ?
    Thanks.

    Javaist wrote:
    Hi ,
    I need to access a file for read/write operations. The file may exist or may not on another computer in my network. I use the File class for accessing the file. (File f = new File("\\192.23.23.23\file.txt");
    My problem is how can I know if I cannot access the file because I have network issues (e.g. The file exists but the network is down so its not accessible) or because the file really dont exist on the given address.
    Since File operations does not throw a specific exception Its hard to know the exact reason for access failure.
    Any suggestions ?Here's a complete hack that only uses File that is completely coupled to Windows and the "\\hostname\dir\file..." syntax. This is not a universal solution and strongly urge you not to use it:
    public class NetworkFileTest {
       public static void main(String[] args) {
          File file = new File("\\\\myhostname\\tmp\\filethatexists");
          if ( file.exists() ) {
             System.out.println("File exists");
          } else {
             if ( hasPathToHost(file) ) {
                System.out.println("File doesn't exist");
             } else {
                System.out.println("No path to host");
       private static boolean hasPathToHost(File file) {
          if ( file.exists() ) {
             return true;
          } else {
             file = file.getParentFile();
             if ( file != null ) {
                return hasPathToHost(file);
             } else {
                return false;
    }This just recursively checks the parent to see if it exists. Once it gets up to the host "directory," it will return false if the network is down, or true otherwise.
    Remember that there's absolutely no way to check if a remote file exists if the network is down, short of carrier pigeons. This will just tell you if the file might exist.
    Edited by: endasil on 9-Oct-2009 10:43 AM

  • Sending stuff over the network

    Hi!
    How do you send int:s, floats and all other basic datatypes trough the network? Is there any package that can make them all to byte[] and back or do you have to write all yourself?

    See java.io.ObjectOutputStream and ObjectInputStream.
    Essentially, these classes "package" java primitives and objects (that implement java.io.Serializable) for output and "unwrap" them for input.

  • Parsing file over the network

    We are using Xerces implementation of jaxp - (xercesImpl.jar, xmlParserAPIs.jar).
    Below is my code:
    DocumentBuilder builder = getBuilder();
    java.io.FileInputStream fi = new java.io.FileInputStream(�file://c$/config/tmp.xml�);
         org.w3c.dom.Document outNode = builder.parse(fi);
         fi.close();
    Inside the tmp.xml is reference to tmp.dtd without specifying any path, just tmp.dtd. The line of code that parses the file throws exception that it can�t find tmp.dtd and it shows me the path where it expects it to be � it is a current user directory. Is there a way of telling the implementation to look somewhere else for files referenced by the file being parsed?.
    Janusz

    yes, intercept the calls to the DTD and point the parser to the right file:
    builder.setEntityResolver(new EntityResolver() {
      public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId)
             throws SAXException, java.io.IOException
        if (systemId.endsWith(".dtd"))
          return new InputSource(new FileInputStream("mypath/"+systemId));
        else return null;

  • Fax over the network with HP LaserJet 400 ColorMFP M475dw

    Hi there, I was trying to send fax over the network with  HP LaserJet 400 ColorMFP M475dw, I have connected the printer/scan/fax on a wired network, just have 3 computers on it, all of them  can scan or print. But I can't find any option to just FAX from Microsoft Word or Adobe Acrobat Reader, going to File ---> Print ---> and select M475dw "FAx", I installed the lasted version of the drivers downloaded from hp.com and there's no way to install this multifunction printer as a FAX.
    So I can't see the FAX on Printers in the control panel of windows.
    I have never got an error message from any computer during the installation process either.
    Does anyone has an idea of what to do here?
    Thanks ahead.

    Thanks for your quick answer, I really appreciate it. But unfortunately, it didn't resolve my problem  
    Actually any of the workstations after complete the installation (with the last version of drivers downloaded just now from hp.com) can't recognize the HP LaserJet Pro 400 Color MFP M475dw, as a fax. I can print and scan over the network, or connecting the printer with a usb cable. I just can't see the icon "HP LaserJet Pro 400 Color MFP M475dw FAX" in Control Panel ---> Devices and Printers.   I did a full installation when I were asked during the installation process... I did then I custom installation and neither of them seems to work to me  
    This is very strange, it never happened to me with any other models of all-in-on (printer/fax/scanner)

  • Relinking files over a network

    This is more of an After Effects issue but I thought someone here might be able to help me or point me in the right direction.
    I have a project that was created entirely with still images (almost 200,000) shot with a Canon 5D.  I converted the CR2 (RAW) to jpegs and edited the project in Final Cut Pro using those jpegs.  I then used Automatic Duck to send the FCP project to After Effects where I used the Batch n Replace script from aescripts.com (thanks Lloyd!) to replace the jpegs with the CR2 files for color correction.  The problem I'm running into is the script creates a new project where the CR2 files have replaced the jpegs, however everything is offline.  The images for each sequence are sorted into folders so I go to the first image in  a folder and tell AE to replace it with the proper file.  AE thinks for a bit and finds and replaces all of the other images in that folder.  Depending on how many images are in a particular folder, it can take anywhere from 5 minutes to several hours for AE to finish.  It took over 4 hours for AE to relink a project with 10 shots/images sequences containing over 12,000 images.
    All of the AE project files are shared via Dropbox with the other Mac Pro in my studio.  I opened one of the projects on the other computer and tried to relink to the CR2 files on my RAID over the network but I had to do each image one by one.  Is there a way to relink the files over the network the same way as if they were on my own computer?

    This is more of an After Effects issue but I thought someone here might be able to help me or point me in the right direction.
    I have a project that was created entirely with still images (almost 200,000) shot with a Canon 5D.  I converted the CR2 (RAW) to jpegs and edited the project in Final Cut Pro using those jpegs.  I then used Automatic Duck to send the FCP project to After Effects where I used the Batch n Replace script from aescripts.com (thanks Lloyd!) to replace the jpegs with the CR2 files for color correction.  The problem I'm running into is the script creates a new project where the CR2 files have replaced the jpegs, however everything is offline.  The images for each sequence are sorted into folders so I go to the first image in  a folder and tell AE to replace it with the proper file.  AE thinks for a bit and finds and replaces all of the other images in that folder.  Depending on how many images are in a particular folder, it can take anywhere from 5 minutes to several hours for AE to finish.  It took over 4 hours for AE to relink a project with 10 shots/images sequences containing over 12,000 images.
    All of the AE project files are shared via Dropbox with the other Mac Pro in my studio.  I opened one of the projects on the other computer and tried to relink to the CR2 files on my RAID over the network but I had to do each image one by one.  Is there a way to relink the files over the network the same way as if they were on my own computer?

Maybe you are looking for