1// excerpts from http://code.google.com/p/muduo/
2//
3// Use of this source code is governed by a BSD-style license
4// that can be found in the License file.
5//
6// Author: Shuo Chen (chenshuo at chenshuo dot com)
7
8#ifndef MUDUO_NET_CHANNEL_H
9#define MUDUO_NET_CHANNEL_H
10
11#include <boost/function.hpp>
12#include <boost/noncopyable.hpp>
13
14#include <datetime/Timestamp.h>
15
16namespace muduo
17{
18
19class EventLoop;
20
21///
22/// A selectable I/O channel.
23///
24/// This class doesn't own the file descriptor.
25/// The file descriptor could be a socket,
26/// an eventfd, a timerfd, or a signalfd
27class Channel : boost::noncopyable
28{
29 public:
30  typedef boost::function<void()> EventCallback;
31  typedef boost::function<void(Timestamp)> ReadEventCallback;
32
33  Channel(EventLoop* loop, int fd);
34  ~Channel();
35
36  void handleEvent(Timestamp receiveTime);
37  void setReadCallback(const ReadEventCallback& cb)
38  { readCallback_ = cb; }
39  void setWriteCallback(const EventCallback& cb)
40  { writeCallback_ = cb; }
41  void setErrorCallback(const EventCallback& cb)
42  { errorCallback_ = cb; }
43  void setCloseCallback(const EventCallback& cb)
44  { closeCallback_ = cb; }
45
46  int fd() const { return fd_; }
47  int events() const { return events_; }
48  void set_revents(int revt) { revents_ = revt; }
49  bool isNoneEvent() const { return events_ == kNoneEvent; }
50
51  void enableReading() { events_ |= kReadEvent; update(); }
52  // void enableWriting() { events_ |= kWriteEvent; update(); }
53  // void disableWriting() { events_ &= ~kWriteEvent; update(); }
54  void disableAll() { events_ = kNoneEvent; update(); }
55
56  // for Poller
57  int index() { return index_; }
58  void set_index(int idx) { index_ = idx; }
59
60  EventLoop* ownerLoop() { return loop_; }
61
62 private:
63  void update();
64
65  static const int kNoneEvent;
66  static const int kReadEvent;
67  static const int kWriteEvent;
68
69  EventLoop* loop_;
70  const int  fd_;
71  int        events_;
72  int        revents_;
73  int        index_; // used by Poller.
74
75  bool eventHandling_;
76
77  ReadEventCallback readCallback_;
78  EventCallback writeCallback_;
79  EventCallback errorCallback_;
80  EventCallback closeCallback_;
81};
82
83}
84#endif  // MUDUO_NET_CHANNEL_H
85