12a18e699SShuo Chen// excerpts from http://code.google.com/p/muduo/
22a18e699SShuo Chen//
32a18e699SShuo Chen// Use of this source code is governed by a BSD-style license
42a18e699SShuo Chen// that can be found in the License file.
52a18e699SShuo Chen//
62a18e699SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
72a18e699SShuo Chen
82a18e699SShuo Chen#ifndef MUDUO_NET_TCPSERVER_H
92a18e699SShuo Chen#define MUDUO_NET_TCPSERVER_H
102a18e699SShuo Chen
112a18e699SShuo Chen#include "Callbacks.h"
122a18e699SShuo Chen#include "TcpConnection.h"
132a18e699SShuo Chen
142a18e699SShuo Chen#include <map>
152a18e699SShuo Chen#include <boost/noncopyable.hpp>
162a18e699SShuo Chen#include <boost/scoped_ptr.hpp>
172a18e699SShuo Chen
182a18e699SShuo Chennamespace muduo
192a18e699SShuo Chen{
202a18e699SShuo Chen
212a18e699SShuo Chenclass Acceptor;
222a18e699SShuo Chenclass EventLoop;
232a18e699SShuo Chen
242a18e699SShuo Chenclass TcpServer : boost::noncopyable
252a18e699SShuo Chen{
262a18e699SShuo Chen public:
272a18e699SShuo Chen
282a18e699SShuo Chen  TcpServer(EventLoop* loop, const InetAddress& listenAddr);
292a18e699SShuo Chen  ~TcpServer();  // force out-line dtor, for scoped_ptr members.
302a18e699SShuo Chen
312a18e699SShuo Chen  /// Starts the server if it's not listenning.
322a18e699SShuo Chen  ///
332a18e699SShuo Chen  /// It's harmless to call it multiple times.
342a18e699SShuo Chen  /// Thread safe.
352a18e699SShuo Chen  void start();
362a18e699SShuo Chen
372a18e699SShuo Chen  /// Set connection callback.
382a18e699SShuo Chen  /// Not thread safe.
392a18e699SShuo Chen  void setConnectionCallback(const ConnectionCallback& cb)
402a18e699SShuo Chen  { connectionCallback_ = cb; }
412a18e699SShuo Chen
422a18e699SShuo Chen  /// Set message callback.
432a18e699SShuo Chen  /// Not thread safe.
442a18e699SShuo Chen  void setMessageCallback(const MessageCallback& cb)
452a18e699SShuo Chen  { messageCallback_ = cb; }
462a18e699SShuo Chen
472a18e699SShuo Chen private:
482a18e699SShuo Chen  /// Not thread safe, but in loop
492a18e699SShuo Chen  void newConnection(int sockfd, const InetAddress& peerAddr);
502a18e699SShuo Chen  void removeConnection(const TcpConnectionPtr& conn);
512a18e699SShuo Chen
522a18e699SShuo Chen  typedef std::map<std::string, TcpConnectionPtr> ConnectionMap;
532a18e699SShuo Chen
542a18e699SShuo Chen  EventLoop* loop_;  // the acceptor loop
552a18e699SShuo Chen  const std::string name_;
562a18e699SShuo Chen  boost::scoped_ptr<Acceptor> acceptor_; // avoid revealing Acceptor
572a18e699SShuo Chen  ConnectionCallback connectionCallback_;
582a18e699SShuo Chen  MessageCallback messageCallback_;
592a18e699SShuo Chen  bool started_;
602a18e699SShuo Chen  int nextConnId_;  // always in loop thread
612a18e699SShuo Chen  ConnectionMap connections_;
622a18e699SShuo Chen};
632a18e699SShuo Chen
642a18e699SShuo Chen}
652a18e699SShuo Chen
662a18e699SShuo Chen#endif  // MUDUO_NET_TCPSERVER_H
67