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_TCPCONNECTION_H
9 #define MUDUO_NET_TCPCONNECTION_H
10 
11+#include "Buffer.h"
12 #include "Callbacks.h"
13 #include "InetAddress.h"
14 
15 #include <boost/any.hpp>
16 #include <boost/enable_shared_from_this.hpp>
17 #include <boost/noncopyable.hpp>
18 #include <boost/scoped_ptr.hpp>
19 #include <boost/shared_ptr.hpp>
20 
21 namespace muduo
22 {
23 
24 class Channel;
25 class EventLoop;
26 class Socket;
27 
28 ///
29 /// TCP connection, for both client and server usage.
30 ///
31 class TcpConnection : boost::noncopyable,
32                       public boost::enable_shared_from_this<TcpConnection>
33 {
34  public:
35   /// Constructs a TcpConnection with a connected sockfd
36   ///
37   /// User should not create this object.
38   TcpConnection(EventLoop* loop,
39                 const std::string& name,
40                 int sockfd,
41                 const InetAddress& localAddr,
42                 const InetAddress& peerAddr);
43   ~TcpConnection();
44 
45   EventLoop* getLoop() const { return loop_; }
46   const std::string& name() const { return name_; }
47   const InetAddress& localAddress() { return localAddr_; }
48   const InetAddress& peerAddress() { return peerAddr_; }
49   bool connected() const { return state_ == kConnected; }
50 
51   void setConnectionCallback(const ConnectionCallback& cb)
52   { connectionCallback_ = cb; }
53 
54   void setMessageCallback(const MessageCallback& cb)
55   { messageCallback_ = cb; }
56 
57   /// Internal use only.
58   void setCloseCallback(const CloseCallback& cb)
59   { closeCallback_ = cb; }
60 
61   // called when TcpServer accepts a new connection
62   void connectEstablished();   // should be called only once
63   // called when TcpServer has removed me from its map
64   void connectDestroyed();  // should be called only once
65 
66  private:
67   enum StateE { kConnecting, kConnected, kDisconnected, };
68 
69   void setState(StateE s) { state_ = s; }
70!  void handleRead(Timestamp receiveTime);
71   void handleWrite();
72   void handleClose();
73   void handleError();
74 
75   EventLoop* loop_;
76   std::string name_;
77   StateE state_;  // FIXME: use atomic variable
78   // we don't expose those classes to client.
79   boost::scoped_ptr<Socket> socket_;
80   boost::scoped_ptr<Channel> channel_;
81   InetAddress localAddr_;
82   InetAddress peerAddr_;
83   ConnectionCallback connectionCallback_;
84   MessageCallback messageCallback_;
85   CloseCallback closeCallback_;
86+  Buffer inputBuffer_;
87 };
88 
89 typedef boost::shared_ptr<TcpConnection> TcpConnectionPtr;
90 
91 }
92 
93 #endif  // MUDUO_NET_TCPCONNECTION_H
94