1354280cfSShuo Chen// excerpts from http://code.google.com/p/muduo/
2354280cfSShuo Chen//
3354280cfSShuo Chen// Use of this source code is governed by a BSD-style license
4354280cfSShuo Chen// that can be found in the License file.
5354280cfSShuo Chen//
6354280cfSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
7354280cfSShuo Chen
8354280cfSShuo Chen#include "Channel.h"
9354280cfSShuo Chen#include "EventLoop.h"
10354280cfSShuo Chen#include "logging/Logging.h"
11354280cfSShuo Chen
12354280cfSShuo Chen#include <sstream>
13354280cfSShuo Chen
14354280cfSShuo Chen#include <poll.h>
15354280cfSShuo Chen
16354280cfSShuo Chenusing namespace muduo;
17354280cfSShuo Chen
18354280cfSShuo Chenconst int Channel::kNoneEvent = 0;
19354280cfSShuo Chenconst int Channel::kReadEvent = POLLIN | POLLPRI;
20354280cfSShuo Chenconst int Channel::kWriteEvent = POLLOUT;
21354280cfSShuo Chen
22354280cfSShuo ChenChannel::Channel(EventLoop* loop, int fdArg)
23354280cfSShuo Chen  : loop_(loop),
24354280cfSShuo Chen    fd_(fdArg),
25354280cfSShuo Chen    events_(0),
26354280cfSShuo Chen    revents_(0),
27354280cfSShuo Chen    index_(-1),
28354280cfSShuo Chen    eventHandling_(false)
29354280cfSShuo Chen{
30354280cfSShuo Chen}
31354280cfSShuo Chen
32354280cfSShuo ChenChannel::~Channel()
33354280cfSShuo Chen{
34354280cfSShuo Chen  assert(!eventHandling_);
35354280cfSShuo Chen}
36354280cfSShuo Chen
37354280cfSShuo Chenvoid Channel::update()
38354280cfSShuo Chen{
39354280cfSShuo Chen  loop_->updateChannel(this);
40354280cfSShuo Chen}
41354280cfSShuo Chen
42354280cfSShuo Chenvoid Channel::handleEvent(Timestamp receiveTime)
43354280cfSShuo Chen{
44354280cfSShuo Chen  eventHandling_ = true;
45354280cfSShuo Chen  if (revents_ & POLLNVAL) {
46354280cfSShuo Chen    LOG_WARN << "Channel::handle_event() POLLNVAL";
47354280cfSShuo Chen  }
48354280cfSShuo Chen
49354280cfSShuo Chen  if ((revents_ & POLLHUP) && !(revents_ & POLLIN)) {
50354280cfSShuo Chen    LOG_WARN << "Channel::handle_event() POLLHUP";
51354280cfSShuo Chen    if (closeCallback_) closeCallback_();
52354280cfSShuo Chen  }
53354280cfSShuo Chen  if (revents_ & (POLLERR | POLLNVAL)) {
54354280cfSShuo Chen    if (errorCallback_) errorCallback_();
55354280cfSShuo Chen  }
56354280cfSShuo Chen  if (revents_ & (POLLIN | POLLPRI | POLLRDHUP)) {
57354280cfSShuo Chen    if (readCallback_) readCallback_(receiveTime);
58354280cfSShuo Chen  }
59354280cfSShuo Chen  if (revents_ & POLLOUT) {
60354280cfSShuo Chen    if (writeCallback_) writeCallback_();
61354280cfSShuo Chen  }
62354280cfSShuo Chen  eventHandling_ = false;
63354280cfSShuo Chen}
64