SocketChannel.write() throws IOException instead of returning 0

I would like your opinion.
When a send buffer is full in the OS, should a channel's write()
return 0, or throw an exception? If an exception, should it be the
same exception (IOException) thrown when truly exceptional events
happen (e.g, a connection drop)?
On Win32, SocketChannel.write() internally calls WSASend(). When
WSASend() returns WSAEWOULDBLOCK, write() throws IOException. I
think it should return zero instead, or at least throw an exception
that can be distinguished easily (by other than parsing the
IOException.getMessage())
Should I submit a bug?
Thanks,
Juan

The java doc for write() says it should return zero. If you have a simple test case that demonstrates the behavior you describe and it is not already in the bug database, then yes. You should file the bug report.

Similar Messages

  • SocketChannel read() throws IOException

    Hi!
    During private SocketChannel channel;
    private ByteBuffer inBuffer;
    channel.read(inBuffer);an IOException (An established connection was aborted by the software in your host machine) was thrown. Does any one know the reason of this unpleasent event? I believe the channel is ok (just created)... maybe I try to write to fast to just created channel? Maybe I should wait for 3-5 seckonds?
    Please help!!!

    You already know the cause - you posted it.
    "An established connection was aborted by the software in your host machine"
    Basically, software (Winsock on Windows), has aborted the connection due to the lovely use of LSPs (Linked/Layered Service Providers) used by anti-virus (and viruses themselves) to control the network services on a computer.
    McAfee VirusScan 8 and Norton AntiVirus 2004 are known to cause this, however, other firewall/anti-x programs can do this.

  • Throws IOException

    What is a best way to write throwing IOException here?
    Can I write try-catch, and after "catch" throw it?
    Is this right?
    I have no idea how to do it with if-clause.
    /** Writes the given apartment data in the file. If the file already
    exists, the old contents are overwritten.
    Parameters:
    apartment - the apartment to be written in the file
    Throws:
    IOException - if other problems arose when handling the file (e.g. the
    file could not be written) */
            public Appartment writeAppartment(Appartment appartment)
                  throws IOException {
                 try {
                    writeStream = new FileOutputStream(filepath);
                    objectStream = new ObjectOutputStream(objectStream);
                    objectStream.writeObject(appartment);
                 } catch (Exception e) {
                   String message ="Writing to file "+filepath+ " failed.";
                   throw new IOException(message);
    }

    Since your method is defined as "throws IOException", why not just get
    rid of the whole try/catch block. Let the caller of writeAppartment
    catch it. You don't seem to be doing anything special with the
    exception when your throwing it, like throwing a custom one, so just
    let java throw it. Plus, what if there is a NullPointerException...it
    would be thrown as an IOException?I see, I haven't understood that when the method is defined as
    "throws IOException", it throws it "automatically".
    So I haven't to do anything.
    But when I call this "throws-method" I have to catch the Exception or
    throw it forward.
    Is that right???
    was meant to be:
    objectStream = new ObjectOutputStream(writeStream);jep, sorry there was an error in that line.

  • Problems with SocketChannel.write(ByteBuffer buff).

    I am using the following version of JDK on Red Hat Linux
    java version "1.4.2_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_01-b06)
    Java HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)
    I am using SocketChannel's write method mentioned above to write data to the SocketChannel. When data is being written on the SocketChannel via this write method and the underlying socket is closed by the receiving endpoint, I expect this method to throw an exception. This method does not throw any exception and returns me 0 as the value of number of bytes written out.
    The way my code is written out, it ends up going in an infinite loop. Now, I can very well fix my code to not run in an infinite loop, but is anybody else seeing this? Is this a valid behavior? Am I doing something wrong?
    Following is the code snippet that writes data to the SocketChannel. Note that writeBuffer is an instance of ByteBuffer and sc is an instance of SocketChannel. Both these variables are member variables in my class:
    public void write(byte[] buff, int offset, int length)
        throws IOException
        int toBeWritten = 0;
        while (length > 0)
            int writeOffset = offset;
            toBeWritten = writeBuffer.remaining();
            if (toBeWritten >= length)
                // All the bytes that are scheduled to be written will be
                // written.
                toBeWritten = length;
                length = 0;
            else
                // Only some of the bytes that are scheduled to be written will
                // be written.
                length -= toBeWritten;
                offset += toBeWritten;
            writeBuffer.put(buff, writeOffset, toBeWritten);
            // toBeWritten is the number of bytes that need to be written out.
            while (writeBuffer.position() != 0)
                // position = toBeWritten.
                writeBuffer.flip();
                // position = 0, limit = toBeWritten.
                int wrote = sc.write(writeBuffer);
                // position = wrote, limit = toBeWritten.
                // Compact the write buffer. It is very much possible that all
                // the bytes have not yet been written out.
                writeBuffer.compact();
                // The data that was written out, is now removed from the write
                // buffer. position = toBeWritten - wrote, limit = capacit
    }Thanks in advance!!

    When ByteBuffer.write(...) return 0, it means this
    socket is closed gracefully by another peer. the
    socket is need to re-connect again.Oh.. I forgot to mention, I am using non blocking SocketChannel. As per the Java docs for write(ByteBuffer src) method in WritableByteChannel:
    "Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer."
    So, I cannot assume that if the write method returns 0, the socket is closed by another peer.

  • Exceptions not thrown on interrupted SocketChannel.write()

    I just noticed a behaviour of java.nio.channels.SocketChannel.write() that makes me wonder. If write() blocks(), and the channel is closed during this blocking by another thread, AsynchronousCloseException should be thrown.
    However, in most cases this does not happen in my little test app. If any part of the data passed to write() has already been written to TCP before the socket was closed, write() returns without exception.
    Similar behaviour is observed with intterupting. If the thread blocked in write() is interrupted by another thread, it returns immediately and has the interrupted Flag set, but in most cases no Exception is thrown.
    ClosedByInterruptException is only thrown if not any part of the data passed to write() has been passed to TCP.
    Is this a bug or a feature ?

    Yes, i'm pretty sure that it blocks. In my test, the server just accepts the connection and then goes to sleep for a looooong time. The client just connects, and sends 10Meg of fata in one write() call. If i do not interrupt the client, it blocks as long as the server sleeps. In this case, this is the client's stack while blocking:
    Thread [main] (Suspended)     
         FileDispatcher.write0(FileDescriptor, long, int) line: not available [native method]     
         SocketDispatcher.write(FileDescriptor, long, int) line: 29     
         IOUtil.writeFromNativeBuffer(FileDescriptor, ByteBuffer, long, NativeDispatcher, Object) line: 104     
         IOUtil.write(FileDescriptor, ByteBuffer, long, NativeDispatcher, Object) line: 75     
         SocketChannelImpl.write(ByteBuffer) line: 334     
         Channels.write(WritableByteChannel, ByteBuffer) line: 60     
         Channels.access$000(WritableByteChannel, ByteBuffer) line: 47     
         Channels$1.write(byte[], int, int) line: 134     
         Channels$1(OutputStream).write(byte[]) line: 58     
         SocketClient.main(String[]) line: 75     If i start another thread before calling write(), that closes the socket after 3 seconds, the following happens: The call of IOUtil.write() returns ( with a value n that i cannot see in the debugger ), This value n is tested inside SocketChannelImpl.write() via (n > 0 || (n == IOStatus.UNAVAILABLE), what return true. For that reason, AbstractInterruptibleChannel.end(boolean), does not throw an exception.
    Once the server wakes up later, it is able to read about 200K from the socket...
    I tried this on a linux system (kernel 2.6.17, glibc 2.4) with jdk 1.6.0_03. I'm now gonna try it under windows, hold on..
    Of course, if anybody is interested, i'll post the test proggy...

  • Log API: StreamHandler.flush() throws IOException ?

    For some network error reason, my logging stopped working and i noticed this exception in the console:
    java.util.logging.ErrorManager: 2
    java.io.IOException: The specified network name is no longer available
            at java.io.FileOutputStream.writeBytes(Native Method)
            at java.io.FileOutputStream.write(Unknown Source)
            at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(Unknown Source)
            at sun.nio.cs.StreamEncoder$CharsetSE.implFlushBuffer(Unknown Source)
            at sun.nio.cs.StreamEncoder$CharsetSE.implFlush(Unknown Source)
            at sun.nio.cs.StreamEncoder.flush(Unknown Source)
            at java.io.OutputStreamWriter.flush(Unknown Source)
            at java.util.logging.StreamHandler.flush(Unknown Source)
            at de.icp.logging.RollingFileHandler.publish(Unknown Source)I looked into the javadoc of StreamHandler.flush() and can't find any documented Exception that is thrown. As IOException is not an unchecked exception, this seems to be a javadoc bug, right?
    My "RollingFileHandler extends StreamHandler and my publish() looks like this:
         * Overwrites super.
        public synchronized void publish(LogRecord record) {
            if (!isLoggable(record)) {
                return;
            //check if we need to rotate
            if (System.currentTimeMillis() >= nextCycle) { //next cycle?
                role();
            super.publish(record);
            flush(); //throws IOException ??????
        }//publish()

    Hm ... i think overwriting reportError() is useful:
         * Overwrites super.
         * Reopen log file in case of an error.
        protected void reportError(String msg, Exception ex, int code) {
            super.reportError(msg, ex, code); //standard behaviour of Handler
           //on logging error, try to reopen the logfile:
            openFile();
            LogRecord record = new LogRecord(Level.WARNING, "Log file re-opened due to error:");
            record.setThrown(ex);
            publish(record);
        }//reportError()

  • DOMparser throws IOException when encounters Hungarian Characters

    Hoi!
    I wrote a piece of code that extracts some
    information from an XML document into a vector of Java classes, using the oracle.xml.parser.v2.DOMParser.
    And it worked. Or seemed to work...
    But when I put some articles in the XML file
    in Hungarian, the parser threw IOException.
    If I remplace the Hungarian characters to
    English "equivalents" a -> a etc., it works.
    I don't know. If XML is made up of Unicode characters, what's the problem with it?
    (The hex code of a was E1 in my text editor,
    as I'm using Win NT :(. )
    can I modify the xml prolog somehow?
    I'd rather not write a conversion program
    from a text file to another.
    Any ideas?
    and here's the code:
    DOMParser theParser = new DOMParser();
    XMLStreamToParse = XMLes.class.getResourceAsStream(xmlDocPath);
    theParser.setValidationMode(false);
    try{
    theParser.parse( XMLStreamToParse );
    //this throws IOException
    null

    What are you using as your test client?The test client is WebStone 1.0. WebStone always downloads the whole response, and reports the size of the response in bytes. From this I can see that when the IO exception occurs, webstone is unable to read the whole response, as it reports a smaller size.
    So, I do not think the problem is that the client has prematurely aborted its download. WebStone doesn't work that way. I think something has gone awry on the server side, and this worries me.

  • SocketChannel.write()

    I've written a non-blocking server and am trying to test it with a client that uses the traditional (blocking) I/O. The problem I'm running into is when the server tries to write data to the client, it seems to take an inordinate amount of time.
    Often times the SocketChannel.write() method will return zero and write nothing to the socket when it has a perfectly good ByteBuffer available to be written. The Javadoc for the SocketChannel.write() states this is normal:
    Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer.
    So I put the following statement in the code:
    while ((retVal = socketChannel.write(outputBuffer)) == 0);However, this is proving to be quite slow, sometimes taking over half a second to complete a write of around 1000 bytes.
    While this solution delivers all of the data, it is slow. Has anybody run into this, and if so, found a better solution?
    Thanks,
    Ken

    I feel compelled to reply to myself to keep this alive, so to add:
    It seems like the delays being experience here would not happen with blocking sockets and that this is a function of NIO. What I don't understand is why socket channel takes so long to know when it can write again. Waiting over half a second for one write of a 1000 byte message is not acceptable.
    Is it because I am not using a Selector? Would that tell me the channel is ready any faster? I wouldn't see why. Or is it because the client application is reading the data too slowly?
    Any help would be appreciated.
    Ken

  • SelectionKey.OP_WRITE versus SocketChannel.write(ByteBuffer)

    I'm writing a small Socket server using Non blocking approach based on the ractor design pattern.
    Many samples use the OP_WRITE on the selection keys to know when the channel is ready to accept writes.
    I use the SocketChannel.write(ByteBuffer) whenever I need to write instead.
    Is there a reason why SelectionKey.OP_WRITE is prefered in the samples??????
    Thanks
    Stéphane

    Rainman4500 wrote:
    I'm writing a small Socket server using Non blocking approach based on the ractor design pattern.
    Many samples use the OP_WRITE on the selection keys to know when the channel is ready to accept writes.
    I use the SocketChannel.write(ByteBuffer) whenever I need to write instead.
    Is there a reason why SelectionKey.OP_WRITE is prefered in the samples??????
    So that you don't attempt a write unless the channel can accept some data from you. In your example, suppose you actually transfer 0 bytes because the output buffer is still full. What do you do then?

  • JarURL.openStream() throws *IOException: no entry name specified*

    <pre>
    I have some code (supplied below) which tries to read contents of a resource
    referred by a URL.
    public class URLTest {
    public static void main(String... args) throws Exception {
    URL u = new URL(args[0]);
    InputStream is = u.openStream();
    // more code goes here:
    If you create a jar file in /tmp/b.jar and run this program as shown below:
    (If your shell treats ! as a special char, then you need to use escape char \ before it)
    java pkg.URLTest <b>jar:file:/tmp/b.jar!/</b>
    it produces the following exception:
    Exception in thread "main" java.io.IOException: no entry name specified
    at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:131)
    at java.net.URL.openStream(URL.java:1007)
    at pkg.URLTest.main(URLTest.java:20)
    But, if you pass the argument as jar:file:/tmp/b.jar!/A.class then it opens a stream
    that points to A.class which is embedded inside b.jar.
    My question is, what is the motivation behind not allowing user to open a stream to
    jar:file:/tmp/b.jar!/ which according to the javadocs of JarURLConnection
    http://java.sun.com/j2se/1.5.0/docs/api/java/net/JarURLConnection.html
    represents a JAR File?
    Thanks,
    Sahoo
    </pre>

    I just also came across this. I don't know the motivation behind it. But it is certainly deliberate.
    This is the source code for JarURLConnection.getInputStream.
    public InputStream getInputStream() throws IOException {
         connect();
         InputStream result = null;
         if (entryName == null) {
              throw new IOException("no entry name specified");
         } else {
              if (jarEntry == null) {
                   throw new FileNotFoundException("JAR entry " + entryName +
                        " not found in " +
                        jarFile.getName());
              result = new JarURLInputStream (jarFile.getInputStream(jarEntry));
         return result;
    }So it will only let you get an InputStream to a file inside the Jar file, not the Jar file itself.
    If you want to do that, then rather than using InputStreams you want to use the JarURLConnection class. My example below shows you how to get at the JarFile and its contents, JarEntry objects,
    URL u = new URL("/tmp/b.jar!/");
    JarURLConnection juc = (JarURLConnection)u.openConnection();
    JarFile jf = juc.getJarFile();
    System.out.println("JarFile: " + jf.getName());
    Enumeration<JarEntry> entries = jf.entries();
    for(JarEntry je = entries.nextElement(); entries.hasMoreElements(); je = entries.nextElement())
         System.out.println("\tJarEntry: " + je.getName());
    }

  • Does SocketChannel.write() block

    I have a server communicating with it's clients using NIO and therefore SocketChannel's. When data are send to clients, the method SocketChannel.write(ByteBuffer) are used. The question is then, does the execution time depend of SocketChannel.write() depend on the speed of the client to receive data? Does the the method block in any way, or does it just send what is possible and then returns?

    If you have the channel in blocking mode, it also depends on how fast the client is reading. If the client isn't reading at all, ultimately its receive buffer will fill up, then the sender's sending buffer will fill, and then the write will block waiting for space in the send buffer; once the client starts reading again, space will become available and the write can complete. That's not to say that every write waits for the completion of every prior read, it's a matter of buffering and windowing, and the effect is rather decoupled because of the presence of two intermediate buffers. However it certainly can occur.

  • Besides throwing exceptions and the "return;" statement

    Besides throwing exceptions and the "*return*" statement, what else clauses could complete a code block abruptly?
    Originally I thought System.exit() should be one of that kind, and I was totally puzzled by the fact that finally clause dose not work with System.exit(). But after a few thoughts, it becomes clear to me that System.exit() dose not even complete a code block, let alone completing a code block abruptly. So is there other logic that could make a code block complete abruptly?
    My question originates from paragraphs in <Thinking in JAVA>, which claim that, I quote,
    "Unfortuantely, there's a flaw in Java's exception implementation. Although exceptions are an indication of a crisis in your program and should never be ignored, it's possible for an exception to simply be lost. This happens with a particular configuration using a finally clause"..."This is a rather serious pitfall, since it means that an exception can be completely lost, and in a far more subtle and difficult -to-detect fashion..."..."Perhaps a future version of Java will repair this problem"...
    After check with JLS, it seams that it is legitimate to ignore the reason for the abrupt completion of the try block, if the corresponding finally block completes abruptly. I think whether this is a "pitfall, flaw" or not depends on how deeply we language users understand the purpose of the finally clause and it is better for me to know all the possible reasons for a code block to complete abruptly.
    So, besides throwing exceptions and the "*return*" statement, what else clauses could complete a code block abruptly?

    warnerja wrote:
    Case 1: Normal flow (no exception is about to be bubbled to the caller before getting to the finally block) - I'd say we want an exception back due to the failure to close the stream.
    Case 2: The finally block was entered through an exception about to be bubbled to the caller - the caller can only get one or the other exception back, either the original exception or the one indicating the failure to close the stream. The finally block has no access to the pending exception however and is unaware of whether there is an exception pending or not. All it knows is an exception occurred during the execution of the finally block, and should throw that or wrap it in another exception - same handling as in Case 1.
    try {
      write();
      flush();
    finally {
      try {
        close();
      catch (...) {
        log();
    }The flush() at the end of try seems kind of redundant, since close() calls flush() anyway. The benefit is that the try statement completion matches the try block ("real work") completion.
    If we get to the end of the try block with no exception, then write() and flush() have succeeded and the data is where it needs to be. All that's left is to release the I/O resource, which will always be done in finally.
    If there's an exception in the try block, it is propagated out, so we know of any failure that occurred doing the "real work." The I/O resource is still released in finally.
    Regardless of how the try block completed, releasing the resource does not affect how the try statement completes, and hence does not supersede how our "real work" completes, which is all we care about. We still log any close() errors for later investigation. What matters to our program is whether all the data was written, and the completion of write() and flush() tells us that.

  • On Windows 7 HttpURLConnection.openConnection() throws IOException

    Hi Team,
    In our application we have a to create httpURLCOnnection (url.openConnection())which works fine on Windows XP but throws IOException on Windows7. Does anybody know which settings need to be enabled on windows 7 to resolve this issue?
    Any response would be appreciated. Thanks in Advance.

    Hello Team,
    I have a specific exception which I get when trying to open a url on Windows 7 with IIS authentication enabled. We get exception when trying to get response code of HTTP Connection
    java.io.IOException: Authentication failure
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    Same code works find on windows XP. Do I need to do any specific settings on Windows7 to work this?
    Thanks in Advance.

  • From edit iPhoto returns to Event page instead of returning to folder.

    When I finish the editing instead of returning to the open folder iPhoto returns to the master events page. I then have to re-open the event and find the edited picture.
    What can I do to eleviate this problem ?

    Bic:
    Check the Events preferences and make sure you have Double click Event: Shows Event photo selected. Then when you go into an event and edit you should go back to the same event with all photos showing when done.
    If you use the Photos mode with Event titles selected to be viewed (will be like the Rolls mode in iPHoto 6) you will always go right back to the same photo and it's neighbors when you edit and finish.
    If you still have problems delete the iPhoto preference file, com.apple.iPhoto.plist, that resides in your User/Library/Preferences folder and try again.
    TIP: For insurance against the iPhoto database corruption that many users have experienced I recommend making a backup copy of the Library6.iPhoto (iPhoto.Library for iPhoto 5 and earlier) database file and keep it current. If problems crop up where iPhoto suddenly can't see any photos or thinks there are no photos in the library, replacing the working Library6.iPhoto file with the backup will often get the library back. By keeping it current I mean backup after each import and/or any serious editing or work on books, slideshows, calendars, cards, etc. That insures that if a problem pops up and you do need to replace the database file, you'll retain all those efforts. It doesn't take long to make the backup and it's good insurance.
    I've created an Automator workflow application (requires Tiger or later), iPhoto dB File Backup, that will copy the selected Library6.iPhoto file from your iPhoto Library folder to the Pictures folder, replacing any previous version of it. It's compatible with iPhoto 6 and 7 libraries and Tiger and Leopard. iPhoto does not have to be closed to run the application, just idle. You can download it at Toad's Cellar. Be sure to read the Read Me pdf file.
    Note: There now an Automator backup application for iPhoto 5 that will work with Tiger or Leopard.

  • L_TO_CREATE_TR displays the error message instead of returning !!

    Hi All,
    The FM L_TO_CREATE_TR is displaying error message instead of returning error/raising exception, as a result the program terminates there, and we are not able to capture the error, and process other items in the loop.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    The above code in line 142 of Include - LL03BF1A, displays the message as Error, if message type is E. Whenever we try to change the SY-MSGTY to I in debug mode, the control again comes to the same point, with same ERROR message, infinitely!!
    An example error message is 'Available quantity in bin is zero'.
    Please provide a solution for the above issue.
    Thanks,
    Prabhakar

    Hi All,
    We have solved the issue, by adding an exception ERROR_MESSAGE before OTHERS, while calling the std. FM L_TO_CREATE_TR.
    For the MESSAGE statement(for msg type E & A) without RAISING clause, the FM will be forced to raise the exception ERROR_MESSAGE. The details of the message can be read from the system parameters(SY).
    Ref: http://help.sap.com/saphelp_nw04/helpdata/en/9f/db98ef35c111d1829f0000e829fbfe/content.htm
    Thanks,
    Prabhakar

Maybe you are looking for

  • Msg=JBO-26061: Error while opening JDBC connection

    I developed an application connecting to a database and the application worked fine. After that I moved the tables into the different database user and server. I opened the application in JDeveloper and I configured the new Database connection and Ne

  • How can I revert to a backup for my icloud account?

    I bought my wife a new IMac which works great.  The problem is that icloud pushed all my phone contacts to her imac after I signed on to my iphone/istore account using her imac.  I deleted all the contacts from her imac (bad move) which in turn delet

  • Creating online help based on external documentation

    Hi there I am in the process of writing a "handbook" for one application I have built. I will write it using MS Word, and it will have detailed information on how to use the app, including screenshots, arrows and other drawing objects. I would like t

  • Incorrect date format in excel reports

    Hi, Some Activity exported from Activity overview to excel have wrong date format. For example Some have 21/04/2008 u2013 Correct Some have 13/04/09 u2013 Incorrect All the dateu2019s in the database seems to be correct like '2008-04-13 00:00:00.000'

  • Change payload NI-XNET CAN

    HI, I am trying to perform some CAN communication with NI-XNET at the frame level.  I have started with the CAN Frame Input Single Point.vi and CAN Frame Output Single Point.vi examples that came with NI-XNET.  I would like to be able to change the p