1e54e5389SShuo Chen// excerpts from http://code.google.com/p/muduo/
2e54e5389SShuo Chen//
3e54e5389SShuo Chen// Use of this source code is governed by a BSD-style license
4e54e5389SShuo Chen// that can be found in the License file.
5e54e5389SShuo Chen//
6e54e5389SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
7e54e5389SShuo Chen
8e54e5389SShuo Chen#ifndef MUDUO_NET_TCPSERVER_H
9e54e5389SShuo Chen#define MUDUO_NET_TCPSERVER_H
10e54e5389SShuo Chen
11e54e5389SShuo Chen#include "Callbacks.h"
12e54e5389SShuo Chen#include "TcpConnection.h"
13e54e5389SShuo Chen
14e54e5389SShuo Chen#include <map>
15e54e5389SShuo Chen#include <boost/noncopyable.hpp>
16e54e5389SShuo Chen#include <boost/scoped_ptr.hpp>
17e54e5389SShuo Chen
18e54e5389SShuo Chennamespace muduo
19e54e5389SShuo Chen{
20e54e5389SShuo Chen
21e54e5389SShuo Chenclass Acceptor;
22e54e5389SShuo Chenclass EventLoop;
23e54e5389SShuo Chen
24e54e5389SShuo Chenclass TcpServer : boost::noncopyable
25e54e5389SShuo Chen{
26e54e5389SShuo Chen public:
27e54e5389SShuo Chen
28e54e5389SShuo Chen  TcpServer(EventLoop* loop, const InetAddress& listenAddr);
29e54e5389SShuo Chen  ~TcpServer();  // force out-line dtor, for scoped_ptr members.
30e54e5389SShuo Chen
31e54e5389SShuo Chen  /// Starts the server if it's not listenning.
32e54e5389SShuo Chen  ///
33e54e5389SShuo Chen  /// It's harmless to call it multiple times.
34e54e5389SShuo Chen  /// Thread safe.
35e54e5389SShuo Chen  void start();
36e54e5389SShuo Chen
37e54e5389SShuo Chen  /// Set connection callback.
38e54e5389SShuo Chen  /// Not thread safe.
39e54e5389SShuo Chen  void setConnectionCallback(const ConnectionCallback& cb)
40e54e5389SShuo Chen  { connectionCallback_ = cb; }
41e54e5389SShuo Chen
42e54e5389SShuo Chen  /// Set message callback.
43e54e5389SShuo Chen  /// Not thread safe.
44e54e5389SShuo Chen  void setMessageCallback(const MessageCallback& cb)
45e54e5389SShuo Chen  { messageCallback_ = cb; }
46e54e5389SShuo Chen
47e54e5389SShuo Chen private:
48e54e5389SShuo Chen  /// Not thread safe, but in loop
49e54e5389SShuo Chen  void newConnection(int sockfd, const InetAddress& peerAddr);
50e54e5389SShuo Chen
51e54e5389SShuo Chen  typedef std::map<std::string, TcpConnectionPtr> ConnectionMap;
52e54e5389SShuo Chen
53e54e5389SShuo Chen  EventLoop* loop_;  // the acceptor loop
54e54e5389SShuo Chen  const std::string name_;
55e54e5389SShuo Chen  boost::scoped_ptr<Acceptor> acceptor_; // avoid revealing Acceptor
56e54e5389SShuo Chen  ConnectionCallback connectionCallback_;
57e54e5389SShuo Chen  MessageCallback messageCallback_;
58e54e5389SShuo Chen  bool started_;
59e54e5389SShuo Chen  int nextConnId_;  // always in loop thread
60e54e5389SShuo Chen  ConnectionMap connections_;
61e54e5389SShuo Chen};
62e54e5389SShuo Chen
63e54e5389SShuo Chen}
64e54e5389SShuo Chen
65e54e5389SShuo Chen#endif  // MUDUO_NET_TCPSERVER_H
66