Communication Non-blocking IO and Blocking IO - Traffic Flow

zhaozj2021-02-16  74

Import java.io.ioException; import java.io.OutputStream; import java.nio.bytebuffer; import java.nio.channels.writablebytechannel;

Public Class ChannelOutputStream Extends OutputStream {

Private WritablebyTechannel Channel CHANNEL

Private Bytebuffer Buffer;

Private int buffersize;

PRIVATE INT BUFFERCOUNT

Public ChannelOutputStream (Writablebytechannel Channel) throws illegalargumentexception {this (channel, 1024);}

public ChannelOutputStream (WritableByteChannel channel, int bufferSize) throws IllegalArgumentException {if (channel == null) {throw new IllegalArgumentException ( "The writable byte channel is null");}

IF (buffersize <1) {throw new IllegalargumentException ("The Buffer Size Is Less Than 1);

This.Channel = Channel; this.buffer = bytebuffer.allocate; this.buffersize = buffersize; this.buffercount = 0;}

Public void write (int b) throws ioException {buffer.put ((byte) b); buffercount ; if (buffercount> = buffersize) {flush ();}}

Public void flush () throws ioException {buffer.flip (); channel.write (buffer); buffer (); buffercount = 0;}

Public void close () throws oException {if (buffercount> 0) {flush ();} channel.close ();}}

转载请注明原文地址:https://www.9cbs.com/read-13809.html

New Post(0)