public int readAndProcess() throws IOException, InterruptedException {
//先对connection进行版本校验,校验成功后读取Header头部信息(得到客户端所用的协议和客户端的标识user)
//,接着读取数据(Call.id和参数params,其中params),然后建立一个Call
while (true) {
/* Read at most one RPC. If the header is not read completely yet
* then iterate until we read first RPC or until there is no data left.
*/
int count = -1;
if (dataLengthBuffer.remaining() > 0) {
count = channelRead(channel, dataLengthBuffer);
if (count < 0 || dataLengthBuffer.remaining() > 0)
return count;
}
if (!versionRead) {//尚未版本验证
//Every connection is expected to send the header.
ByteBuffer versionBuffer = ByteBuffer.allocate(1);
count = channelRead(channel, versionBuffer);
if (count <= 0) {
return count;
}
int version = versionBuffer.get(0);
//要读取BufferByte前要先flip下
dataLengthBuffer.flip();//.flip();一定得有,如果没有,就是从最后开始读取的,当然读出来的都是byte=0时候的字符。
//通过buffer.flip();这个语句,就能把buffer的当前位置更改为buffer缓冲区的第一个位置
if (!HEADER.equals(dataLengthBuffer) || version != CURRENT_VERSION) {
//Warning is ok since this is not supposed to happen.
LOG.warn("Incorrect header or version mismatch from " +
hostAddress + ":" + remotePort +
" got version " + version +
" expected version " + CURRENT_VERSION);
return -1;
}
dataLengthBuffer.clear();//清除内容
versionRead = true;//验证版本了
continue;
}
if (data == null) {//分配新的data
dataLengthBuffer.flip();
dataLength = dataLengthBuffer.getInt();
if (dataLength == Client.PING_CALL_ID) {
dataLengthBuffer.clear();
return 0; //ping message
}
data = ByteBuffer.allocate(dataLength);
incRpcCount(); // Increment the rpc count
}
count = channelRead(channel, data);//读数据
if (data.remaining() == 0) {//因为分配刚好的dataLength,所有正常情况会无剩余空间
dataLengthBuffer.clear();
data.flip();
if (headerRead) {//头部已经处理过了
processData();//处理数据
data = null;
return count;
} else {
processHeader();
headerRead = true;
data = null;
// Authorize the connection
try {//尝试授权
authorize(user, header);//user已创建成功
if (LOG.isDebugEnabled()) {
LOG.debug("Successfully authorized " + header);
}
} catch (AuthorizationException ae) {//授权失败
authFailedCall.connection = this;
setupResponse(authFailedResponse, authFailedCall,
Status.FATAL, null,
ae.getClass().getName(), ae.getMessage());
responder.doRespond(authFailedCall);
// Close this connection
return -1;
}
continue;
}
}
return count;
}
}
Server.Listener是一个用于监听新的连接的线程。该线程在run里面循环处理在channel上的事件。当事件为新连接(即key.isAcceptable()=true)时,调用doAccpet接收请求(为channel注册OP_READ监听读,然后根据注册得到的SelectionKey和channel创建一个新的Server.Connection,然后将这个连接加入到连接集合connectionList内【handler进程是从这个list上取出数据进行处理的】);当事件为读事件(即key.isReadable()=true)调用doRead读取connection上的数据(其实是调用connection.readAndProcess进行读);当没有监听到事件时,会调用cleanupConnections(false)清理掉长时间不响应的连接。
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
while (running) {
SelectionKey key = null;
try {
/*Selector通过select方法通知我们我们感兴趣的事件发生了。
nKeys = selector.select();
如果有我们注册的事情发生了,它的传回值就会大于0*/
selector.select();
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
key = iter.next();
iter.remove();
try {
if (key.isValid()) {//此键是否有效
if (key.isAcceptable())//通道是否已准备好接受新的套接字连接。
doAccept(key);//接受一个新连接,为通道注册读事件,建立新连接并将新连接加入connectionList
else if (key.isReadable())//测试此键的通道是否已准备好进行读取。
doRead(key);//调用Connection.readAndProcess读取call的数据,建立新call
}
} catch (IOException e) {
}
key = null;
}
} catch (OutOfMemoryError e) {
// we can run out of memory if we have too many threads
// log the event and sleep for a minute and give
// some thread(s) a chance to finish
LOG.warn("Out of Memory in server select", e);
closeCurrentConnection(key, e);
cleanupConnections(true);
try { Thread.sleep(60000); } catch (Exception ie) {}
} catch (InterruptedException e) {
if (running) { // unexpected -- log it
LOG.info(getName() + " caught: " +
StringUtils.stringifyException(e));
}
} catch (Exception e) {
closeCurrentConnection(key, e);
}
cleanupConnections(false);
}
LOG.info("Stopping " + this.getName());
synchronized (this) {
try {//善后工作
acceptChannel.close();
selector.close();
} catch (IOException e) { }
selector= null;
acceptChannel= null;
// clean up all connections
while (!connectionList.isEmpty()) {
closeConnection(connectionList.remove(0));
}
}
}
