Skip to content

Instantly share code, notes, and snippets.

@He-Pin
Last active December 10, 2015 19:18
Show Gist options
  • Save He-Pin/4480415 to your computer and use it in GitHub Desktop.
Save He-Pin/4480415 to your computer and use it in GitHub Desktop.
public void write(ByteBuffer data){
if (data == null) {
return;
}
writeBuffers.offer(data);
//start an notify
writer.execute(new Runnable() {
@Override
public void run() {
try {
selectionKey = udtSocketChannel.register(selector, SelectionKey.OP_WRITE);
for(;;){
//use the selector and send the data out via the selection key
int selected = selector.select();
if (selected == 0) {
continue;
}
selector.selectedKeys().clear();
ByteBuffer byteBuffer = writeBuffers.poll();
if (byteBuffer == null) {
// System.out.println("null");
selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_WRITE);
return;
}/*else{
System.out.println("size :"+byteBuffer.limit());
}*/
//write the data out
int writed = 0;
try {
for(;;){
if (byteBuffer.hasRemaining()) {
writed += udtSocketChannel.write(byteBuffer);
udtHandler.onDataWrited(writed);
}else {
return;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (ClosedChannelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
/*System.out.println( "send Rate Mbps:"+monitorUDT.mbpsSendRate());
System.out.println( "recv Rate Mbps:"+monitorUDT.mbpsReceiveRate());*/
}
public void write(final ByteBuffer data ,final SocketChannel socketChannel) throws IOException{
if (data == null) {
return;
}
//start an notify
if (selector == null) {
selector = SelectorProviderUDT.STREAM.openSelector();
}
woker.execute(new Runnable() {
@Override
public void run() {
try {
selectionKey = socketChannel.register(selector, SelectionKey.OP_WRITE);
//use the selector and send the data out via the selection key
selector.select();
selector.selectedKeys().clear();
//write the data out
int writed = 0;
try {
for(;;){
if (data.hasRemaining()) {
writed += socketChannel.write(data);
udtHandler.onDataWrited(writed);
}else {
selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_WRITE);
return;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClosedChannelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//System.out.println( "send Rate Mbps:"+monitorUDT.mbpsSendRate());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment