Acceptor.cc 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#include "Acceptor.h" 965c497a3SShuo Chen 1065c497a3SShuo Chen#include "logging/Logging.h" 1165c497a3SShuo Chen#include "EventLoop.h" 1265c497a3SShuo Chen#include "InetAddress.h" 1365c497a3SShuo Chen#include "SocketsOps.h" 1465c497a3SShuo Chen 1565c497a3SShuo Chen#include <boost/bind.hpp> 1665c497a3SShuo Chen 1765c497a3SShuo Chenusing namespace muduo; 1865c497a3SShuo Chen 1965c497a3SShuo ChenAcceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr) 2065c497a3SShuo Chen : loop_(loop), 2165c497a3SShuo Chen acceptSocket_(sockets::createNonblockingOrDie()), 2265c497a3SShuo Chen acceptChannel_(loop, acceptSocket_.fd()), 2365c497a3SShuo Chen listenning_(false) 2465c497a3SShuo Chen{ 2565c497a3SShuo Chen acceptSocket_.setReuseAddr(true); 2665c497a3SShuo Chen acceptSocket_.bindAddress(listenAddr); 2765c497a3SShuo Chen acceptChannel_.setReadCallback( 2865c497a3SShuo Chen boost::bind(&Acceptor::handleRead, this)); 2965c497a3SShuo Chen} 3065c497a3SShuo Chen 3165c497a3SShuo Chenvoid Acceptor::listen() 3265c497a3SShuo Chen{ 3365c497a3SShuo Chen loop_->assertInLoopThread(); 3465c497a3SShuo Chen listenning_ = true; 3565c497a3SShuo Chen acceptSocket_.listen(); 3665c497a3SShuo Chen acceptChannel_.enableReading(); 3765c497a3SShuo Chen} 3865c497a3SShuo Chen 3965c497a3SShuo Chenvoid Acceptor::handleRead() 4065c497a3SShuo Chen{ 4165c497a3SShuo Chen loop_->assertInLoopThread(); 4265c497a3SShuo Chen InetAddress peerAddr(0); 4365c497a3SShuo Chen //FIXME loop until no more 4465c497a3SShuo Chen int connfd = acceptSocket_.accept(&peerAddr); 4565c497a3SShuo Chen if (connfd >= 0) 4665c497a3SShuo Chen { 4765c497a3SShuo Chen // string hostport = peerAddr.toHostPort(); 4865c497a3SShuo Chen // LOG_TRACE << "Accepts of " << hostport; 4965c497a3SShuo Chen if (newConnectionCallback_) 5065c497a3SShuo Chen { 5165c497a3SShuo Chen newConnectionCallback_(connfd, peerAddr); 5265c497a3SShuo Chen } 5365c497a3SShuo Chen else 5465c497a3SShuo Chen { 5565c497a3SShuo Chen sockets::close(connfd); 5665c497a3SShuo Chen } 5765c497a3SShuo Chen } 5865c497a3SShuo Chen} 5965c497a3SShuo Chen 60