1e54e5389SShuo Chen// excerpts from http://code.google.com/p/muduo/
2e54e5389SShuo Chen//
3e54e5389SShuo Chen// Use of this source code is governed by a BSD-style license
4e54e5389SShuo Chen// that can be found in the License file.
5e54e5389SShuo Chen//
6e54e5389SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
7e54e5389SShuo Chen
8e54e5389SShuo Chen#include "TcpConnection.h"
9e54e5389SShuo Chen
10e54e5389SShuo Chen#include "logging/Logging.h"
11e54e5389SShuo Chen#include "Channel.h"
12e54e5389SShuo Chen#include "EventLoop.h"
13e54e5389SShuo Chen#include "Socket.h"
14e54e5389SShuo Chen
15e54e5389SShuo Chen#include <boost/bind.hpp>
16e54e5389SShuo Chen
17e54e5389SShuo Chen#include <errno.h>
18e54e5389SShuo Chen#include <stdio.h>
19e54e5389SShuo Chen
20e54e5389SShuo Chenusing namespace muduo;
21e54e5389SShuo Chen
22e54e5389SShuo ChenTcpConnection::TcpConnection(EventLoop* loop,
23e54e5389SShuo Chen                             const std::string& nameArg,
24e54e5389SShuo Chen                             int sockfd,
25e54e5389SShuo Chen                             const InetAddress& localAddr,
26e54e5389SShuo Chen                             const InetAddress& peerAddr)
27e54e5389SShuo Chen  : loop_(CHECK_NOTNULL(loop)),
28e54e5389SShuo Chen    name_(nameArg),
29e54e5389SShuo Chen    state_(kConnecting),
30e54e5389SShuo Chen    socket_(new Socket(sockfd)),
31e54e5389SShuo Chen    channel_(new Channel(loop, sockfd)),
32e54e5389SShuo Chen    localAddr_(localAddr),
33e54e5389SShuo Chen    peerAddr_(peerAddr)
34e54e5389SShuo Chen{
35e54e5389SShuo Chen  LOG_DEBUG << "TcpConnection::ctor[" <<  name_ << "] at " << this
36e54e5389SShuo Chen            << " fd=" << sockfd;
37e54e5389SShuo Chen  channel_->setReadCallback(
38e54e5389SShuo Chen      boost::bind(&TcpConnection::handleRead, this));
39e54e5389SShuo Chen}
40e54e5389SShuo Chen
41e54e5389SShuo ChenTcpConnection::~TcpConnection()
42e54e5389SShuo Chen{
43e54e5389SShuo Chen  LOG_DEBUG << "TcpConnection::dtor[" <<  name_ << "] at " << this
44e54e5389SShuo Chen            << " fd=" << channel_->fd();
45e54e5389SShuo Chen}
46e54e5389SShuo Chen
47e54e5389SShuo Chenvoid TcpConnection::connectEstablished()
48e54e5389SShuo Chen{
49e54e5389SShuo Chen  loop_->assertInLoopThread();
50e54e5389SShuo Chen  assert(state_ == kConnecting);
51e54e5389SShuo Chen  setState(kConnected);
52e54e5389SShuo Chen  channel_->enableReading();
53e54e5389SShuo Chen
54e54e5389SShuo Chen  connectionCallback_(shared_from_this());
55e54e5389SShuo Chen}
56e54e5389SShuo Chen
57e54e5389SShuo Chenvoid TcpConnection::handleRead()
58e54e5389SShuo Chen{
59e54e5389SShuo Chen  char buf[65536];
600615e80eSShuo Chen  ssize_t n = ::read(channel_->fd(), buf, sizeof buf);
61e54e5389SShuo Chen  messageCallback_(shared_from_this(), buf, n);
62e54e5389SShuo Chen  // FIXME: close connection if n == 0
63e54e5389SShuo Chen}
64e54e5389SShuo Chen
65