Java ByteBuffer Write writeFromBuffer(SocketChannel channel, ByteBuffer buf, int sleepMsecs)

Here you can find the source of writeFromBuffer(SocketChannel channel, ByteBuffer buf, int sleepMsecs)

Description

write From Buffer

License

BSD License

Declaration

static public int writeFromBuffer(SocketChannel channel, ByteBuffer buf, int sleepMsecs) 

Method Source Code


//package com.java2s;
//License from project: BSD License 

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class Main {
    static public int writeFromBuffer(SocketChannel channel, ByteBuffer buf, int sleepMsecs) {

        if (channel == null || buf.limit() == 0) {
            return -1;
        }/*from w ww  .  j ava  2  s  .com*/

        int totWritten = 0;
        buf.rewind();

        // write until capacity reached

        while (totWritten < buf.limit()) {

            int nWritten;
            try {
                nWritten = channel.write(buf);
            } catch (IOException e) {
                System.err.println("ERROR - NioUtils.writeFromBuffer");
                System.err.println(" Writing buffer to channel");
                return -1;
            } catch (BufferOverflowException e) {
                System.err.println("ERROR - NioUtils.writeFromBuffer");
                System.err.println("  Buffer overflow");
                return -1;
            }
            if (nWritten < 0) {
                return -1;
            }
            totWritten += nWritten;

            // sleep if stalled

            if (nWritten == sleepMsecs) {
                _sleep(10);
            }
        }

        // rewind buffer, in case it will be reused

        buf.rewind();

        return 0;

    }

    static private void _sleep(int msecs) {

        Thread t = Thread.currentThread();
        try {
            t.sleep(msecs);
        } catch (InterruptedException e) {
        }

    }
}

Related

  1. writeFile(ByteBuffer data, File destination)
  2. writeFile(File file, ByteBuffer bb)
  3. writeFile(File file, ByteBuffer buffer)
  4. writeFileFragment(FileChannel fc, long pos, ByteBuffer fragment)
  5. writeFloat(ByteBuffer buffer, float f)
  6. writeFully(@Nonnull final FileChannel dst, @Nonnull final ByteBuffer src, @Nonnegative final long position)
  7. writeFully(ByteBuffer buf, WritableByteChannel out)
  8. writeFully(ByteBuffer buffer, WritableByteChannel channel)
  9. writeFully(FileChannel channel, ByteBuffer fileInfosBuffer)