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_TCPCLIENT_H
9#define MUDUO_NET_TCPCLIENT_H
10
11#include <boost/noncopyable.hpp>
12
13#include "thread/Mutex.h"
14#include "TcpConnection.h"
15
16namespace muduo
17{
18
19class Connector;
20typedef boost::shared_ptr<Connector> ConnectorPtr;
21
22class TcpClient : boost::noncopyable
23{
24 public:
25  TcpClient(EventLoop* loop,
26            const InetAddress& serverAddr);
27  ~TcpClient();  // force out-line dtor, for scoped_ptr members.
28
29  void connect();
30  void disconnect();
31  void stop();
32
33  TcpConnectionPtr connection() const
34  {
35    MutexLockGuard lock(mutex_);
36    return connection_;
37  }
38
39  bool retry() const;
40  void enableRetry() { retry_ = true; }
41
42  /// Set connection callback.
43  /// Not thread safe.
44  void setConnectionCallback(const ConnectionCallback& cb)
45  { connectionCallback_ = cb; }
46
47  /// Set message callback.
48  /// Not thread safe.
49  void setMessageCallback(const MessageCallback& cb)
50  { messageCallback_ = cb; }
51
52  /// Set write complete callback.
53  /// Not thread safe.
54  void setWriteCompleteCallback(const WriteCompleteCallback& cb)
55  { writeCompleteCallback_ = cb; }
56
57 private:
58  /// Not thread safe, but in loop
59  void newConnection(int sockfd);
60  /// Not thread safe, but in loop
61  void removeConnection(const TcpConnectionPtr& conn);
62
63  EventLoop* loop_;
64  ConnectorPtr connector_; // avoid revealing Connector
65  ConnectionCallback connectionCallback_;
66  MessageCallback messageCallback_;
67  WriteCompleteCallback writeCompleteCallback_;
68  bool retry_;   // atmoic
69  bool connect_; // atomic
70  // always in loop thread
71  int nextConnId_;
72  mutable MutexLock mutex_;
73  TcpConnectionPtr connection_; // @BuardedBy mutex_
74};
75
76}
77
78#endif  // MUDUO_NET_TCPCLIENT_H
79