165c497a3SShuo Chen// excerpts from http://code.google.com/p/muduo/
265c497a3SShuo Chen//
365c497a3SShuo Chen// Use of this source code is governed by a BSD-style license
465c497a3SShuo Chen// that can be found in the License file.
565c497a3SShuo Chen//
665c497a3SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
765c497a3SShuo Chen
865c497a3SShuo Chen#include "Channel.h"
965c497a3SShuo Chen#include "EventLoop.h"
1065c497a3SShuo Chen#include "logging/Logging.h"
1165c497a3SShuo Chen
1265c497a3SShuo Chen#include <sstream>
1365c497a3SShuo Chen
1465c497a3SShuo Chen#include <poll.h>
1565c497a3SShuo Chen
1665c497a3SShuo Chenusing namespace muduo;
1765c497a3SShuo Chen
1865c497a3SShuo Chenconst int Channel::kNoneEvent = 0;
1965c497a3SShuo Chenconst int Channel::kReadEvent = POLLIN | POLLPRI;
2065c497a3SShuo Chenconst int Channel::kWriteEvent = POLLOUT;
2165c497a3SShuo Chen
2265c497a3SShuo ChenChannel::Channel(EventLoop* loop, int fdArg)
2365c497a3SShuo Chen  : loop_(loop),
2465c497a3SShuo Chen    fd_(fdArg),
2565c497a3SShuo Chen    events_(0),
2665c497a3SShuo Chen    revents_(0),
2765c497a3SShuo Chen    index_(-1),
2865c497a3SShuo Chen    eventHandling_(false)
2965c497a3SShuo Chen{
3065c497a3SShuo Chen}
3165c497a3SShuo Chen
3265c497a3SShuo ChenChannel::~Channel()
3365c497a3SShuo Chen{
3465c497a3SShuo Chen  assert(!eventHandling_);
3565c497a3SShuo Chen}
3665c497a3SShuo Chen
3765c497a3SShuo Chenvoid Channel::update()
3865c497a3SShuo Chen{
3965c497a3SShuo Chen  loop_->updateChannel(this);
4065c497a3SShuo Chen}
4165c497a3SShuo Chen
42714cd85fSShuo Chenvoid Channel::handleEvent(Timestamp receiveTime)
4365c497a3SShuo Chen{
4465c497a3SShuo Chen  eventHandling_ = true;
4565c497a3SShuo Chen  if (revents_ & POLLNVAL) {
4665c497a3SShuo Chen    LOG_WARN << "Channel::handle_event() POLLNVAL";
4765c497a3SShuo Chen  }
4865c497a3SShuo Chen
4965c497a3SShuo Chen  if ((revents_ & POLLHUP) && !(revents_ & POLLIN)) {
5065c497a3SShuo Chen    LOG_WARN << "Channel::handle_event() POLLHUP";
5165c497a3SShuo Chen    if (closeCallback_) closeCallback_();
5265c497a3SShuo Chen  }
5365c497a3SShuo Chen  if (revents_ & (POLLERR | POLLNVAL)) {
5465c497a3SShuo Chen    if (errorCallback_) errorCallback_();
5565c497a3SShuo Chen  }
5665c497a3SShuo Chen  if (revents_ & (POLLIN | POLLPRI | POLLRDHUP)) {
57714cd85fSShuo Chen    if (readCallback_) readCallback_(receiveTime);
5865c497a3SShuo Chen  }
5965c497a3SShuo Chen  if (revents_ & POLLOUT) {
6065c497a3SShuo Chen    if (writeCallback_) writeCallback_();
6165c497a3SShuo Chen  }
6265c497a3SShuo Chen  eventHandling_ = false;
6365c497a3SShuo Chen}
64