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_TCPSERVER_H
9#define MUDUO_NET_TCPSERVER_H
10
11#include "Callbacks.h"
12#include "TcpConnection.h"
13
14#include <map>
15#include <boost/noncopyable.hpp>
16#include <boost/scoped_ptr.hpp>
17
18namespace muduo
19{
20
21class Acceptor;
22class EventLoop;
23
24class TcpServer : boost::noncopyable
25{
26 public:
27
28  TcpServer(EventLoop* loop, const InetAddress& listenAddr);
29  ~TcpServer();  // force out-line dtor, for scoped_ptr members.
30
31  /// Starts the server if it's not listenning.
32  ///
33  /// It's harmless to call it multiple times.
34  /// Thread safe.
35  void start();
36
37  /// Set connection callback.
38  /// Not thread safe.
39  void setConnectionCallback(const ConnectionCallback& cb)
40  { connectionCallback_ = cb; }
41
42  /// Set message callback.
43  /// Not thread safe.
44  void setMessageCallback(const MessageCallback& cb)
45  { messageCallback_ = cb; }
46
47 private:
48  /// Not thread safe, but in loop
49  void newConnection(int sockfd, const InetAddress& peerAddr);
50  void removeConnection(const TcpConnectionPtr& conn);
51
52  typedef std::map<std::string, TcpConnectionPtr> ConnectionMap;
53
54  EventLoop* loop_;  // the acceptor loop
55  const std::string name_;
56  boost::scoped_ptr<Acceptor> acceptor_; // avoid revealing Acceptor
57  ConnectionCallback connectionCallback_;
58  MessageCallback messageCallback_;
59  bool started_;
60  int nextConnId_;  // always in loop thread
61  ConnectionMap connections_;
62};
63
64}
65
66#endif  // MUDUO_NET_TCPSERVER_H
67