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