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 void setCloseCallback(const CloseCallback& cb) 58 { closeCallback_ = cb; } 59 60 // called when TcpServer accepts a new connection 61 void connectEstablished(); // should be called only once 62 // called when TcpServer has removed me from its map 63 void connectDestroyed(); // should be called only once 64 65 private: 66 enum StateE { kConnecting, kConnected, kDisconnected, }; 67 68 void setState(StateE s) { state_ = s; } 69 void handleRead(); 70 void handleWrite(); 71 void handleClose(); 72 void handleError(); 73 74 EventLoop* loop_; 75 std::string name_; 76 StateE state_; // FIXME: use atomic variable 77 // we don't expose those classes to client. 78 boost::scoped_ptr<Socket> socket_; 79 boost::scoped_ptr<Channel> channel_; 80 InetAddress localAddr_; 81 InetAddress peerAddr_; 82 ConnectionCallback connectionCallback_; 83 MessageCallback messageCallback_; 84 CloseCallback closeCallback_; 85}; 86 87typedef boost::shared_ptr<TcpConnection> TcpConnectionPtr; 88 89} 90 91#endif // MUDUO_NET_TCPCONNECTION_H 92