TcpServer.h revision 65c497a3
165c497a3SShuo Chen// excerpts from http://code.google.com/p/muduo/
265c497a3SShuo Chen//
365c497a3SShuo Chen// Use of this source code is governed by a BSD-style license
465c497a3SShuo Chen// that can be found in the License file.
565c497a3SShuo Chen//
665c497a3SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
765c497a3SShuo Chen
865c497a3SShuo Chen#ifndef MUDUO_NET_TCPSERVER_H
965c497a3SShuo Chen#define MUDUO_NET_TCPSERVER_H
1065c497a3SShuo Chen
1165c497a3SShuo Chen#include "Callbacks.h"
1265c497a3SShuo Chen#include "TcpConnection.h"
1365c497a3SShuo Chen
1465c497a3SShuo Chen#include <map>
1565c497a3SShuo Chen#include <boost/noncopyable.hpp>
1665c497a3SShuo Chen#include <boost/scoped_ptr.hpp>
1765c497a3SShuo Chen
1865c497a3SShuo Chennamespace muduo
1965c497a3SShuo Chen{
2065c497a3SShuo Chen
2165c497a3SShuo Chenclass Acceptor;
2265c497a3SShuo Chenclass EventLoop;
2365c497a3SShuo Chen
2465c497a3SShuo Chenclass TcpServer : boost::noncopyable
2565c497a3SShuo Chen{
2665c497a3SShuo Chen public:
2765c497a3SShuo Chen
2865c497a3SShuo Chen  TcpServer(EventLoop* loop, const InetAddress& listenAddr);
2965c497a3SShuo Chen  ~TcpServer();  // force out-line dtor, for scoped_ptr members.
3065c497a3SShuo Chen
3165c497a3SShuo Chen  /// Starts the server if it's not listenning.
3265c497a3SShuo Chen  ///
3365c497a3SShuo Chen  /// It's harmless to call it multiple times.
3465c497a3SShuo Chen  /// Thread safe.
3565c497a3SShuo Chen  void start();
3665c497a3SShuo Chen
3765c497a3SShuo Chen  /// Set connection callback.
3865c497a3SShuo Chen  /// Not thread safe.
3965c497a3SShuo Chen  void setConnectionCallback(const ConnectionCallback& cb)
4065c497a3SShuo Chen  { connectionCallback_ = cb; }
4165c497a3SShuo Chen
4265c497a3SShuo Chen  /// Set message callback.
4365c497a3SShuo Chen  /// Not thread safe.
4465c497a3SShuo Chen  void setMessageCallback(const MessageCallback& cb)
4565c497a3SShuo Chen  { messageCallback_ = cb; }
4665c497a3SShuo Chen
4765c497a3SShuo Chen private:
4865c497a3SShuo Chen  /// Not thread safe, but in loop
4965c497a3SShuo Chen  void newConnection(int sockfd, const InetAddress& peerAddr);
5065c497a3SShuo Chen  void removeConnection(const TcpConnectionPtr& conn);
5165c497a3SShuo Chen
5265c497a3SShuo Chen  typedef std::map<std::string, TcpConnectionPtr> ConnectionMap;
5365c497a3SShuo Chen
5465c497a3SShuo Chen  EventLoop* loop_;  // the acceptor loop
5565c497a3SShuo Chen  const std::string name_;
5665c497a3SShuo Chen  boost::scoped_ptr<Acceptor> acceptor_; // avoid revealing Acceptor
5765c497a3SShuo Chen  ConnectionCallback connectionCallback_;
5865c497a3SShuo Chen  MessageCallback messageCallback_;
5965c497a3SShuo Chen  bool started_;
6065c497a3SShuo Chen  int nextConnId_;  // always in loop thread
6165c497a3SShuo Chen  ConnectionMap connections_;
6265c497a3SShuo Chen};
6365c497a3SShuo Chen
6465c497a3SShuo Chen}
6565c497a3SShuo Chen
6665c497a3SShuo Chen#endif  // MUDUO_NET_TCPSERVER_H
67