你可以做这样的事情
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<Integer, AsynchronousSocketChannel> {
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) {
}
};
为什么?你想解决什么问题?你可以用'BufferedReader'每秒读取数百万行。这还不够吗? – EJP
@EJP:我想读取异步。我不想阻止等待通过套接字接收的一行文本。我希望在接收完整行文本时调用我的代码。 –
@ giorgio-b如果你没有从套接字中读取数据,那么接收完整行会发生什么? –