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 /// Set write complete callback. 48 /// Not thread safe. 49 void setWriteCompleteCallback(const WriteCompleteCallback& cb) 50 { writeCompleteCallback_ = cb; } 51 52 private: 53 /// Not thread safe, but in loop 54 void newConnection(int sockfd, const InetAddress& peerAddr); 55 void removeConnection(const TcpConnectionPtr& conn); 56 57 typedef std::map<std::string, TcpConnectionPtr> ConnectionMap; 58 59 EventLoop* loop_; // the acceptor loop 60 const std::string name_; 61 boost::scoped_ptr<Acceptor> acceptor_; // avoid revealing Acceptor 62 ConnectionCallback connectionCallback_; 63 MessageCallback messageCallback_; 64 WriteCompleteCallback writeCompleteCallback_; 65 bool started_; 66 int nextConnId_; // always in loop thread 67 ConnectionMap connections_; 68}; 69 70} 71 72#endif // MUDUO_NET_TCPSERVER_H 73