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_CONNECTOR_H 9#define MUDUO_NET_CONNECTOR_H 10 11#include "InetAddress.h" 12#include "TimerId.h" 13 14#include <boost/enable_shared_from_this.hpp> 15#include <boost/function.hpp> 16#include <boost/noncopyable.hpp> 17#include <boost/scoped_ptr.hpp> 18 19namespace muduo 20{ 21 22class Channel; 23class EventLoop; 24 25class Connector : boost::noncopyable 26{ 27 public: 28 typedef boost::function<void (int sockfd)> NewConnectionCallback; 29 30 Connector(EventLoop* loop, const InetAddress& serverAddr); 31 ~Connector(); 32 33 void setNewConnectionCallback(const NewConnectionCallback& cb) 34 { newConnectionCallback_ = cb; } 35 36 void start(); // can be called in any thread 37 void restart(); // must be called in loop thread 38 void stop(); // can be called in any thread 39 40 const InetAddress& serverAddress() const { return serverAddr_; } 41 42 private: 43 enum States { kDisconnected, kConnecting, kConnected }; 44 static const int kMaxRetryDelayMs = 30*1000; 45 static const int kInitRetryDelayMs = 500; 46 47 void setState(States s) { state_ = s; } 48 void startInLoop(); 49 void connect(); 50 void connecting(int sockfd); 51 void handleWrite(); 52 void handleError(); 53 void retry(int sockfd); 54 int removeAndResetChannel(); 55 void resetChannel(); 56 57 EventLoop* loop_; 58 InetAddress serverAddr_; 59 bool connect_; // atomic 60 States state_; // FIXME: use atomic variable 61 boost::scoped_ptr<Channel> channel_; 62 NewConnectionCallback newConnectionCallback_; 63 int retryDelayMs_; 64 TimerId timerId_; 65}; 66typedef boost::shared_ptr<Connector> ConnectorPtr; 67 68} 69 70#endif // MUDUO_NET_CONNECTOR_H 71