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 21namespace muduo 22{ 23 24class Channel; 25class EventLoop; 26class Socket; 27 28/// 29/// TCP connection, for both client and server usage. 30/// 31class 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 send(const void* message, size_t len); 52 // Thread safe. 53 void send(const std::string& message); 54 // Thread safe. 55 void shutdown(); 56 57 void setConnectionCallback(const ConnectionCallback& cb) 58 { connectionCallback_ = cb; } 59 60 void setMessageCallback(const MessageCallback& cb) 61 { messageCallback_ = cb; } 62 63 /// Internal use only. 64 void setCloseCallback(const CloseCallback& cb) 65 { closeCallback_ = cb; } 66 67 // called when TcpServer accepts a new connection 68 void connectEstablished(); // should be called only once 69 // called when TcpServer has removed me from its map 70 void connectDestroyed(); // should be called only once 71 72 private: 73 enum StateE { kConnecting, kConnected, kDisconnecting, kDisconnected, }; 74 75 void setState(StateE s) { state_ = s; } 76 void handleRead(Timestamp receiveTime); 77 void handleWrite(); 78 void handleClose(); 79 void handleError(); 80 void sendInLoop(const std::string& message); 81 void shutdownInLoop(); 82 83 EventLoop* loop_; 84 std::string name_; 85 StateE state_; // FIXME: use atomic variable 86 // we don't expose those classes to client. 87 boost::scoped_ptr<Socket> socket_; 88 boost::scoped_ptr<Channel> channel_; 89 InetAddress localAddr_; 90 InetAddress peerAddr_; 91 ConnectionCallback connectionCallback_; 92 MessageCallback messageCallback_; 93 CloseCallback closeCallback_; 94 Buffer inputBuffer_; 95 Buffer outputBuffer_; 96}; 97 98typedef boost::shared_ptr<TcpConnection> TcpConnectionPtr; 99 100} 101 102#endif // MUDUO_NET_TCPCONNECTION_H 103