java 异步读写_Java:用于读写行的异步I / O通道

你可以做这样的事情

public void nioAsyncParse(AsynchronousSocketChannel channel, final int bufferSize) throws IOException, ParseException, InterruptedException {

ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);

BufferConsumer consumer = new BufferConsumer(byteBuffer, bufferSize);

channel.read(consumer.buffer(), 0l, channel, consumer);

}

class BufferConsumer implements CompletionHandler {

private ByteBuffer bytes;

private StringBuffer chars;

private int limit;

private long position;

private DateFormat frmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public BufferConsumer(ByteBuffer byteBuffer, int bufferSize) {

bytes = byteBuffer;

chars = new StringBuffer(bufferSize);

frmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

limit = bufferSize;

position = 0l;

}

public ByteBuffer buffer() {

return bytes;

}

@Override

public synchronized void completed(Integer result, AsynchronousSocketChannel channel) {

if (result!=-1) {

bytes.flip();

final int len = bytes.limit();

int i = 0;

try {

for (i = 0; i < len; i++) {

byte by = bytes.get();

if (by=='\n') {

// ***

// The code used to process the line goes here

// ***

chars.setLength(0);

}

else {

chars.append((char) by);

}

}

}

catch (Exception x) {

System.out.println("Caught exception " + x.getClass().getName() + " " + x.getMessage() + " i=" + String.valueOf(i) + ", limit=" + String.valueOf(len) + ", position="+String.valueOf(position));

}

if (len==limit) {

bytes.clear();

position += len;

channel.read(bytes, position, channel, this);

}

else {

try {

channel.close();

}

catch (IOException e) { }

bytes.clear();

buffers.add(bytes);

}

}

else {

try {

channel.close();

}

catch (IOException e) { }

bytes.clear();

buffers.add(bytes);

}

}

@Override

public void failed(Throwable e, AsynchronousSocketChannel channel) {

}

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值