OutputStreamWriter doesn't seem to obey flush()

I'm writing characters to a BufferedWriter whose underlying OutputStream is a TCP socket connection. At the other end of the socket, I see each full buffer of data, but I don't see the last (partial) buffer of data. On the client side, I verify with debug code that I'm writing all the data to the stream, and then I flush the BufferedWriter and all its underlying output streams. But the last partial buffer of data never makes it to the other end of the connection.
here's my client code:
                                int i = 0;
                          char[] buf = new char[1024];
                                oos = new ObjectOutputStream(tcpSock.getOutputStream());
                     <some code that reads and writes objects on oos>
                                out = new BuffereredWriter(new OutputStreamWriter(OOS));
                                while((i=in.read(buf))!=-1) {
                          out.write(buf, 0, i);
                          System.err.println("Client: wrote " + i + " chars");
                                out.flush();
                                oos.flush();
                                tcpSock.getOutputStream().flush();server code:
                                 byte[] buf = new byte[1024];
                           int i = 0;
                                 long bytesRead = 0;
            <verify that fileSize = number of bytes sent by client>
                                 ois = new ObjectInputStream(tcpConnection.getInputStream());
                                 while((i=ois.read(buf))!=-1 && bytesRead + i < fileSize ) {
                              fos.write(buf, 0, i);
                              bytesRead = bytesRead + i;
                              System.err.println("Server: bytes read = " + bytesRead);
                         fos.flush();output shows that only 1024 bytes are read, and the output file only has 1024 characters.
I have a different method on the client that does the same exact thing except it transfers bytes out an OutputStream rather than chars out a BufferedWriter/OutputStreamWriter, and it does not have this problem. The last partial buffer is read by the server in this other method.

It turns out this failure is occurring under much simpler conditions, with a byte[] to byte[] transfer over an ObjectOutputSream to ObjectInputStream connection. I created a self-contained test program that replicates the problem.
The code below includes a client and server, communicating on port 8090. The client reads a file called "test_in.txt" from the directory where the program is executing and streams the file to the server. The server then streams it to the file "test_out.txt" in the same directory .
I captured the TCP segments and saw that all data from the file was going to the server. But the server code does not read the last partial buffer of data. I believe the problem is with checking for end of file at the server. Since objects are transferred over the same connection before and after the file is streamed, the client sends the file size and the server is supposed to stop reading after all expected bytes are read. There is something wrong with the looping condition I'm using to do this, but I can't figure out why it doesn't work as coded.
This test needs to be run with more than 1024 bytes in the file "test_in.txt", to re-create the problem. You can download the test file I used from http://mysite.verizon.net/midnightjava/test.html. When the file is copied as "test_out.txt", if the last thing you see is not a quote from Forest Gump, the last buffer was not read.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class FileCopyTest {
     int port = 8090;
     InetAddress ip = null;
     public static void main (String[] args){
          FileCopyTest test = new FileCopyTest();
          Server server = test.new Server();
          server.start();
          Client client = test.new Client();
          client.start();
     class Client extends Thread{
          public void run(){
               FileInputStream fis = null;
               File testFile = new File("test_in.txt");
               Long fileSize = new Long(testFile.length());
               ObjectOutputStream oos = null;
               ObjectInputStream ois = null;
               Socket sock = new Socket();
               String s = "", s2 = "";
               System.out.println("Client: file size = " + fileSize);
               try {
                    fis = new FileInputStream(testFile);
               } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               try {
                    ip = InetAddress.getByName("localhost");
               } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               try {
                    sock = new Socket(ip, port);
                    oos = new ObjectOutputStream(sock.getOutputStream());
                    ois = new ObjectInputStream(sock.getInputStream());
                    oos.writeObject(fileSize);
                    s = (String) ois.readObject();
               } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               int i = 0;
               byte[] buf = new byte[1024];
               long bytesWritten = 0;
               try {
                    while((i=fis.read(buf))!=-1) {
                         oos.write(buf, 0, i);
                         bytesWritten = bytesWritten + i;
                         System.err.println("Client: writing " + i + " bytes");
                         System.err.println("Client: total bytes written: " + bytesWritten);               
                    s2 = (String) ois.readObject();
                    fis.close();
                    oos.flush();
                    sock.getOutputStream().flush();
                    oos.close();
                    ois.close();
                    sock.close();
               } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               System.out.println("Client received: " + s + " and " + s2);
     class Server extends Thread{
          public void run(){
               ObjectOutputStream oos = null;
               ObjectInputStream ois = null;
               FileOutputStream fos = null;
               Long fileSize = null;
               try {
                    ServerSocket server = new ServerSocket(port);
                    Socket sock = server.accept();
                    oos = new ObjectOutputStream(sock.getOutputStream());
                    ois = new ObjectInputStream(sock.getInputStream());
                    fileSize = (Long) ois.readObject();
                    oos.writeObject(new String("received file size"));
                    System.out.println("Server: recevied file size: " + fileSize.longValue());
                    fos = new FileOutputStream("test_out.txt");
                    byte[] buf = new byte[1024];
                    int i = 0;
                    long bytesRead = 0;
                    do {
                         i = ois.read(buf);
                         fos.write(buf, 0, i);
                         bytesRead = bytesRead + i;
                         System.err.println("Server: writing " + i + " bytes");
                         System.err.println("Server: total bytes written: " + bytesRead);
                    } while ( bytesRead  <= fileSize.longValue());
                    fos.close();
                    oos.writeObject(new String("Received file"));
                    oos.close();
                    ois.close();
                    sock.close();
               } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
}

Similar Messages

  • Back from service, case doesn't seem right

    I just got my macbook pro back from service, maybe a week or two ago. Since its been back I've noticed the case really doesn't seem like its fitting together right. I've got gaps between various pieces of the case and have parts that don't really fit flush anymore. It wasn't like this when I sent it out
    If I call apple do you think they'll fix it? They could easily just ignore it and blame it on me, but it definitely wasn't like this when I sent it off, and the more I look at it the more it really seems put together wrong.

    I'm guessing that there is a gap on the front of the machine where the bottom case fits with the top case (the part with the keyboard & trackpad).
    Once the unit is popped open, it doesn't close quite like it did when it was first assembled. That's because there are 4 clips that are on the front inside lip that get slightly worn when the machine is popped open. I'm also guessing that there is a glue of somesort that is run lightly around the seams to ensure flush enclosure.
    There are stories that even without servicing that these gaps form after time.
    If you go and demand that apple fix it, they will. They will have to replace the top and bottom case. This fix could take quite a bit longer as it would need to be sent out to the depot. All of the innerds need to come out to replace the bottom case. But...they'll do it if you demand it.

  • Mini dvi to s-video/composite adapter doesn't seem to work?

    basically i'm trying to hook my rather new 2.53 ghz mac mini to my tv, which basically has rca inputs. so, having seen several laptops hooked to this tv as simply as using an s-video to composite adapter, i figured it would be as simple as getting the mini dvi to composite adapter and i'd be good. well, for some reason this doesn't seem to do anything. the other weird thing is that when i hook the cable from the composite adapter to the tv, i get a buzz out of the speakers as the connection is being made. why is a video signal having anything to do with the audio? plugging my playstation 2 into the same input works fine. why the difference?

    Boece wrote:
    !http://images2.monoprice.com/productmediumimages/47241.jpg!
    +
    !http://images2.monoprice.com/productmediumimages/48501.jpg!
    That's the setup I've used. Works great for video and photos, but webpage text can be difficult to read.
    I used the yellow composite input rather than the s-video. My old tv is inside an “entertainment center” type tv stand and is so friggin heavy, it’s a pain in the axx to move, so I just used the composite plug on the front of my tv. Since the Mac mini is sitting in front of the tv it works great:-)
    http://discussions.apple.com/thread.jspa?threadID=2430645&tstart=0
    Message was edited by: James Press1

  • Need lightroom 4.4 asmac is 10.6.8 and not compatible with anything higher. Does this come with the creative cloud? Would really like a disc but that doesn't seem to happen anymore. Currently have cs4 and d7100 hence need 4.4 to open raw Any idea

    need lightroom 4.4 asmac is 10.6.8 and not compatible with anything higher. Does this come with the creative cloud? Would really like a disc but that doesn't seem to happen anymore. Currently have cs4 and d7100 hence need 4.4 to open raw Any ideas? Is this now customer service or does adobe have a customer service team . Site not user friendly. Thanks

    Graham Giles wrote:
    Have you seen this type of problem before? I think it could be a serious issue for anyone in a similar position.
    No; but then, I've not had occasion to use TDM. I've been using firerwire drives for over 10 years, both FW400 and FW800, with no issues except a bit of instability using a B&W G3 machine.
    TDM should be safe. Using cautious, manual copying of files from the Target machine to the Host machine should not result in unexpected loss of files or damage to the Target drive's directories. It should behave exactly the same as if it were an external (to the Host) firewire drive.
    •  I don't suppose there is anything I can do to 'put back' lost items from a separate Time Machine drive which has an up to date backup on it.
    There is probably a way to do that - seems to me that's one of the reasons for a Time Machine volume.
    On the other hand, if the Time Machine volume is rigidly linked to the now-absent OS on the original drive, there may be no way to effectively access the files in the TM archive.
    I know that using a cloned drive would work well in this instance.
    I have no experience with Time Machine, so perhaps someone who has will chime in with suggestions.
    With the machine in TDM with the other machine, have you tried running Disk Utility to see if you can effect repairs to the drive?

  • Wacom Tablet doesn't seem to work all of the time?

    I have a Wacom Intuos 3 tablet, not more than a year old. I recently installed it onto my Macbook Pro and it worked fine, but when I unplugged it and came back to work with it later, it doesn't seem to work. The mouse doesn't respond to where I click on the pad.
    So, I've reinstalled this a couple of times and was able to make it work perfectly, but today when I went back to work in photoshop, it doesn't seem to be responding again.
    Does anyone have any tips? I know that Leopard likes you to eject USB devices instead of just pulling them out of the slot, but I don't see anywhere to eject it.
    Does anyone know what's up?

    Downloaded a driver from website, tablet works now.

  • HT3235 I just bought a Micro-DVI to video adapter to try and hook my MacBook Pro 13" I bought mid 2009 to my old TV, the adapter doesn't seem to fit any of the connections, is this the right adapter?

    I just bought a Micro-DVI to video adapter to try and hook my MacBook Pro 13" that I bought in mid 2009 to my old TV (svideo), the adapter doesn't seem to fit any of the connections on my macBook pro, is right adapter?

    Shootist007 wrote:
    Apple doesn't offer a MDP to AV or componet connect . Only DVI and VGA. They also don't offer one to HDMI. You have to go aftermarket to get one to HDMI.
    Quite right, but as the OP does not have component or composite connections not important.
    To the OP, this does work, but is not the cheapest, and as it appears that Apple no longer sell an SVideo adaptor cable 3rd party it will have to be.

  • 1.burned a hole in my screen can I get this repaired?  2. Even though I have it set to open up to a blank screen, no web pages, my computer (safari) continuously opens with multiple safari sites open. It doesn't seem to matter what I do, it just reverts

    1. I burned a small hole in my screen, is that fixable/replaceable? 2. Even though I have my 15" MacBook Pro set to open to empty screen when I open Safari, it constantly opens multiple previous pages. It doesn't seem to matter what I do it just reverts back to opening multiple pages. Major security risk, my bank pages have popped back up after my computer has been shut down, account numbers and all. I took my computer to an Apple store and the genious there tols me...      "honey, you can't hold your laptop on your lap, that's the problem, it's getting too hot" he honestly said that. Could someone please help me? Thanks

    Apple doesn't call its portable machines 'notebooks' instead of 'laptops' for nothing - using a MacBook Pro in your lap can cause some burns on your skin, poor ventilation, etc. So use it on a hard flat surface - not your lap, pillows, bedclothes, etc.
    As for burning a hole in your screen, you'll have to revisit the Apple Store and see how much they would charge for a new screen. It's likely to be a bit expensive.
    And if you've Safari set to re-open tabs when you restart, you can disable this feature -> Safari-Preferences-General.
    Good luck,
    Clinton

  • How does Azure Compute Emulator (or the Azure one) determine if a role is web project or something else ("The Web Role in question doesn't seem to be a web application type project")?

    I'm not sure if this is F# specific or something else, but what could cause the following error message when trying to debug locally an Azure cloud service:
    The Web Role in question doesn't seem to be a web application type project.
    I added an empty F# web api Project to a solution (which adds Global.asax etc., I added an OWIN startup class Startup etc.) and then from an existing
    cloud service project I picked Roles and
    chose Add
    -> Web Role Project in solution, which finds the F# web project (its project type guids are 349C5851-65DF-11DA-9384-00065B846F21 and F2A71F9B-5D33-465A-A702-920D77279786),
    of which the first one seem to be exactly the GUID that defines a web application type.
    However, when I try to start the cloud project locally, I get the aforementioned error message. I have a C# Web Role project that will start when I remove the F# project. I also have F# worker
    role projects that start with the C# web role project if I remove this F# web role project. If I set the F# web project as a startup project,
    it starts and runs as one would expect, normally.
    Now, it makes me wonder if this is something with F# or could this error message appears in C# too, but I didn't find anything on Google. What kind of checks are there when starting the emulator and which one needs
    failing to prompt the aforementioned message? Can anyone shed light into this?
    Sudet ulvovat -- karavaani kulkee

    Sudet,
    Yeah you are right, the GUID mentioned seems to be correct and the first one i.e. {349C5851-65DF-11DA-9384-00065B846F21} means the web application project which compute emulator uses to determine while spawning up role instances.
    You might want to compare the csproj of your C# and F# web projects which might give some pointers.
    Are you able to run your F# web project locally in IIS? If yes then you will definitely be able to run it on azure so I will recommend to test it in IIS Express first.
    Here are some other tips which you can refer or see If you are yet to do those settings
    1. Turn on the IIS Express - You can do it by navigating to project properties
    2. Install Dependent ASP.NET NuGets / Web Api dependencies (If there are any missing), Reference System.Web assembly
    Also I will suggest to refer this nice article about how to create a F# web Api project
    http://blog.ploeh.dk/2013/08/23/how-to-create-a-pure-f-aspnet-web-api-project/
    Hope this helps you.
    Bhushan | http://www.passionatetechie.blogspot.com | http://twitter.com/BhushanGawale

  • My apple tv is registering on my tv - i can see it on my system info screen but the apple tv doesn't show up, as well my imac doesn't seem to let me share - so i don't know whats wrong, why my apple tv isn't working

    anybody able to help me with my setup for apple tv.  i've followed the directions in the guide and my tv doesn't seem to register in part.  it's weird because my tv system info identifies the apple tv but the screen never went black and it doesn't show anything, too, my imac doesn't seem to register the apple tv unit either

    I would try connecting it to another tv to see if it works there if it does
    then likely your tv can't handle the default resolution and you should lower it on the other tv
    if not then you should connect it by usb to the computer and use itunes to restore it's firmware

  • Safari on my iPhone 6 running 8.02 doesn't seem to work right. Some Java scripts don't show correctly and they do on other browsers I have downloaded. I tried almost everything and nothing seems to work to fix it. Please help.

    Some websites like the one of my college uses JavaScripts and they seem to load correctly to a certain point but then not really. For example in one it would say select an option from the left menu. And I do it hut nothing happens. But when I go to the same website in another browser on my phone. The JavaScript works completely and allows me to see whatever I was clickig on that menu. I have seen that there are other websites being affected too. I tried clearing my cookies and data. even restarted my phone. And doesn't seem to work. I don't know how change the configuration any more to make it work like normal. At first I thought it was my school's website but it never got fixed. And now I realized is my safari browser! I wanna keep using it since I am really familiar with It. If someone knows how to fix this please let me know!
    Thanks

    You can reset the SMC and see if that helps. If it's a unibody or Retina, follow the method for "a battery you should not remove yourself."
    http://support.apple.com/kb/ht3964

  • I'm using iphoto9.1.3 but now it doesn't seem to work, whenever I try to open it, it just shows loading, but never loads. Can anybody help me with this ?

    I'm using iphoto9.1.3 but now it doesn't seem to work, whenever I try to open it, it just shows loading, but never loads. Can anybody help me with this ?    

    Option 1
    Back Up and try rebuild the library: hold down the command and option (or alt) keys while launching iPhoto. Use the resulting dialogue to rebuild. Choose to Rebuild iPhoto Library Database from automatic backup.
    If that fails:
    Option 2
    Download iPhoto Library Manager and use its rebuild function. This will create a new library based on data in the albumdata.xml file. Not everything will be brought over - no slideshows, books or calendars, for instance - but it should get all your albums and keywords back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one. .
    Regards
    TD

  • TS3991 iWork doesn't seem to recognize that I already have the pages, keynote, and numbers apps so I can't use iCloud to sync my documents.  How to get my apps recognized?

    iWork doesn't seem to recognize that I already have the pages, keynote, and numbers apps so I can't use iCloud to sync my documents.  How to get my apps recognized?

    Do you have both the OS X and iOS versions of each of them?

  • The image came up on my screen saying that I need to connect my iPod to iTunes, but I have a passcode, so it won't allow me to. And I want to try and turn it off, but my touch screen doesn't seem to be working either. HELP!

    The image came up on my screen saying that I need to connect my iPod to iTunes, but I have a passcode, so it won't allow me to. And I want to try and turn it off, but my touch screen doesn't seem to be working either, so I can't even turn it off since you need to "slide to power off." HELP! I'm leaving on Thursday morning for six and a half weeks, and I absolutely need my iPod with me. I was just at the Apple store today for problems I was having with ANOTHER product, and I don't really want to drive all the way out to where my nearest store is (which is not very near) if I can figure this out at home. My iPod was working totally fine earlier today and last night, so I don't know what happened! Please, please, PLEASE HELP!

    Now it's allowing me to reboot (hold down power button and home button and restart), but every time it just comes up to the same thing: the connect to iTunes page. Which is not possible. And I refuse to restore my iPod. PLEASE HELP.

  • IPhoto suddenly doesn't seem to recognize my camera, and essentially freezes. The only thing that makes sense is that another person in my house imported using a different camera and that changed things somehow. Ideas?

    iPhoto suddenly doesn't seem to recognize my camera, and essentially freezes. The only thing that makes sense is that another person in my house imported using a different camera and that changed things somehow. Ideas?

    Hi There!
    The camera is a Panasonic Lumix. I don't have a USB card reader. I did try and different port although not a different cable.
    I did remember one additional thing. I plugged my camera in at work to a PC. It was after that, when I came home, that the iPhoto wasn't working when I connected my camera to our iMac/iPhoto at home. I think this may have caused the problem.
    Cheers!

  • How do I open my itunes account on a new computer without having to buy all new songs? It doesn't seem fair to have to buy all the same songs a second time if they are already purchased by me and I just want them on my new computer!

    How do I open my itunes account on a new computer without having to buy all new songs? It doesn't seem fair to have to buy all the same songs a second time if they are already purchased by me and I just want them on my new computer!

    There's a few different ways. The following document is worth checking through:
    iTunes: How to move your music to a new computer

Maybe you are looking for

  • Adjusting photos in iweb

    i would like to know why i can't adjust my photos once i drop them into a page in IWEB.  The editing bar at the bottom once highlighted opens up but the bar to move exposure or brightness or anything else on it does not work.  nothing happens!

  • PI 7.1 Upgrade Mount Point

    Hi. Im upgrading a 7.0 PI system to 7.1, and all was going well until the system asked about the mount points. I have tried everything - the cds, the downloaded product. Nothing seems to recognise the 'SAP Kernel DVD Unicode' folders /cds. Its able t

  • External LDAP Server

    Hello. Is it possible to configure WebLogic to use external LDAP server, which in turn is "built in" in other WebLogic (at other physical machine)? And if it is possible, can I use OracleInternetDirectoryAuthenticator provider for this? (sorry for my

  • Formatting a combined dual chart - which svg commands necessary?

    Hello all, I have a combined dual chart (two columns and one line) as shown in the picture below. I'd like to format the following things: - color of columns (costs in one color and Incoming Order List in a different) - color of outer ticks of both y

  • Special character in print

    Hello SAP gurus. For some inspection description we are using capital delta (Trangle) it is comming in print preview of certificate but after taking print of same in out put we are getting 'A' insted of delta. Please suggest what may be reason of sam