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