1b37003a7SShuo Chen// excerpts from http://code.google.com/p/muduo/
2b37003a7SShuo Chen//
3b37003a7SShuo Chen// Use of this source code is governed by a BSD-style license
4b37003a7SShuo Chen// that can be found in the License file.
5b37003a7SShuo Chen//
6b37003a7SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
7b37003a7SShuo Chen
8b37003a7SShuo Chen#include "Channel.h"
9b37003a7SShuo Chen#include "EventLoop.h"
10b37003a7SShuo Chen#include "logging/Logging.h"
11b37003a7SShuo Chen
12b37003a7SShuo Chen#include <sstream>
13b37003a7SShuo Chen
14b37003a7SShuo Chen#include <poll.h>
15b37003a7SShuo Chen
16b37003a7SShuo Chenusing namespace muduo;
17b37003a7SShuo Chen
18b37003a7SShuo Chenconst int Channel::kNoneEvent = 0;
19b37003a7SShuo Chenconst int Channel::kReadEvent = POLLIN | POLLPRI;
20b37003a7SShuo Chenconst int Channel::kWriteEvent = POLLOUT;
21b37003a7SShuo Chen
22b37003a7SShuo ChenChannel::Channel(EventLoop* loop, int fdArg)
23b37003a7SShuo Chen  : loop_(loop),
24b37003a7SShuo Chen    fd_(fdArg),
25b37003a7SShuo Chen    events_(0),
26b37003a7SShuo Chen    revents_(0),
27b37003a7SShuo Chen    index_(-1),
28b37003a7SShuo Chen    eventHandling_(false)
29b37003a7SShuo Chen{
30b37003a7SShuo Chen}
31b37003a7SShuo Chen
32b37003a7SShuo ChenChannel::~Channel()
33b37003a7SShuo Chen{
34b37003a7SShuo Chen  assert(!eventHandling_);
35b37003a7SShuo Chen}
36b37003a7SShuo Chen
37b37003a7SShuo Chenvoid Channel::update()
38b37003a7SShuo Chen{
39b37003a7SShuo Chen  loop_->updateChannel(this);
40b37003a7SShuo Chen}
41b37003a7SShuo Chen
42b37003a7SShuo Chenvoid Channel::handleEvent(Timestamp receiveTime)
43b37003a7SShuo Chen{
44b37003a7SShuo Chen  eventHandling_ = true;
45b37003a7SShuo Chen  if (revents_ & POLLNVAL) {
46b37003a7SShuo Chen    LOG_WARN << "Channel::handle_event() POLLNVAL";
47b37003a7SShuo Chen  }
48b37003a7SShuo Chen
49b37003a7SShuo Chen  if ((revents_ & POLLHUP) && !(revents_ & POLLIN)) {
50b37003a7SShuo Chen    LOG_WARN << "Channel::handle_event() POLLHUP";
51b37003a7SShuo Chen    if (closeCallback_) closeCallback_();
52b37003a7SShuo Chen  }
53b37003a7SShuo Chen  if (revents_ & (POLLERR | POLLNVAL)) {
54b37003a7SShuo Chen    if (errorCallback_) errorCallback_();
55b37003a7SShuo Chen  }
56b37003a7SShuo Chen  if (revents_ & (POLLIN | POLLPRI | POLLRDHUP)) {
57b37003a7SShuo Chen    if (readCallback_) readCallback_(receiveTime);
58b37003a7SShuo Chen  }
59b37003a7SShuo Chen  if (revents_ & POLLOUT) {
60b37003a7SShuo Chen    if (writeCallback_) writeCallback_();
61b37003a7SShuo Chen  }
62b37003a7SShuo Chen  eventHandling_ = false;
63b37003a7SShuo Chen}
64