Acceptor.cc revision a1bde736
1a1bde736SShuo Chen// excerpts from http://code.google.com/p/muduo/ 2a1bde736SShuo Chen// 3a1bde736SShuo Chen// Use of this source code is governed by a BSD-style license 4a1bde736SShuo Chen// that can be found in the License file. 5a1bde736SShuo Chen// 6a1bde736SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 7a1bde736SShuo Chen 8a1bde736SShuo Chen#include "Acceptor.h" 9a1bde736SShuo Chen 10a1bde736SShuo Chen#include "logging/Logging.h" 11a1bde736SShuo Chen#include "EventLoop.h" 12a1bde736SShuo Chen#include "InetAddress.h" 13a1bde736SShuo Chen#include "SocketsOps.h" 14a1bde736SShuo Chen 15a1bde736SShuo Chen#include <boost/bind.hpp> 16a1bde736SShuo Chen 17a1bde736SShuo Chenusing namespace muduo; 18a1bde736SShuo Chen 19a1bde736SShuo ChenAcceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr) 20a1bde736SShuo Chen : loop_(loop), 21a1bde736SShuo Chen acceptSocket_(sockets::createNonblockingOrDie()), 22a1bde736SShuo Chen acceptChannel_(loop, acceptSocket_.fd()), 23a1bde736SShuo Chen listenning_(false) 24a1bde736SShuo Chen{ 25a1bde736SShuo Chen acceptSocket_.setReuseAddr(true); 26a1bde736SShuo Chen acceptSocket_.bindAddress(listenAddr); 27a1bde736SShuo Chen acceptChannel_.setReadCallback( 28a1bde736SShuo Chen boost::bind(&Acceptor::handleRead, this)); 29a1bde736SShuo Chen} 30a1bde736SShuo Chen 31a1bde736SShuo Chenvoid Acceptor::listen() 32a1bde736SShuo Chen{ 33a1bde736SShuo Chen loop_->assertInLoopThread(); 34a1bde736SShuo Chen listenning_ = true; 35a1bde736SShuo Chen acceptSocket_.listen(); 36a1bde736SShuo Chen acceptChannel_.enableReading(); 37a1bde736SShuo Chen} 38a1bde736SShuo Chen 39a1bde736SShuo Chenvoid Acceptor::handleRead() 40a1bde736SShuo Chen{ 41a1bde736SShuo Chen loop_->assertInLoopThread(); 42a1bde736SShuo Chen InetAddress peerAddr(0); 43a1bde736SShuo Chen //FIXME loop until no more 44a1bde736SShuo Chen int connfd = acceptSocket_.accept(&peerAddr); 45a1bde736SShuo Chen if (connfd >= 0) { 46a1bde736SShuo Chen if (newConnectionCallback_) { 47a1bde736SShuo Chen newConnectionCallback_(connfd, peerAddr); 48a1bde736SShuo Chen } else { 49a1bde736SShuo Chen sockets::close(connfd); 50a1bde736SShuo Chen } 51a1bde736SShuo Chen } 52a1bde736SShuo Chen} 53a1bde736SShuo Chen 54