Channel.h revision b37003a7
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  bool isWriting() const { return events_ & kWriteEvent; }
56
57  // for Poller
58  int index() { return index_; }
59  void set_index(int idx) { index_ = idx; }
60
61  EventLoop* ownerLoop() { return loop_; }
62
63 private:
64  void update();
65
66  static const int kNoneEvent;
67  static const int kReadEvent;
68  static const int kWriteEvent;
69
70  EventLoop* loop_;
71  const int  fd_;
72  int        events_;
73  int        revents_;
74  int        index_; // used by Poller.
75
76  bool eventHandling_;
77
78  ReadEventCallback readCallback_;
79  EventCallback writeCallback_;
80  EventCallback errorCallback_;
81  EventCallback closeCallback_;
82};
83
84}
85#endif  // MUDUO_NET_CHANNEL_H
86