TcpConnection.cc revision e54e5389
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#include "TcpConnection.h"
9
10#include "logging/Logging.h"
11#include "Channel.h"
12#include "EventLoop.h"
13#include "Socket.h"
14
15#include <boost/bind.hpp>
16
17#include <errno.h>
18#include <stdio.h>
19
20using namespace muduo;
21
22TcpConnection::TcpConnection(EventLoop* loop,
23                             const std::string& nameArg,
24                             int sockfd,
25                             const InetAddress& localAddr,
26                             const InetAddress& peerAddr)
27  : loop_(CHECK_NOTNULL(loop)),
28    name_(nameArg),
29    state_(kConnecting),
30    socket_(new Socket(sockfd)),
31    channel_(new Channel(loop, sockfd)),
32    localAddr_(localAddr),
33    peerAddr_(peerAddr)
34{
35  LOG_DEBUG << "TcpConnection::ctor[" <<  name_ << "] at " << this
36            << " fd=" << sockfd;
37  channel_->setReadCallback(
38      boost::bind(&TcpConnection::handleRead, this));
39}
40
41TcpConnection::~TcpConnection()
42{
43  LOG_DEBUG << "TcpConnection::dtor[" <<  name_ << "] at " << this
44            << " fd=" << channel_->fd();
45}
46
47void TcpConnection::connectEstablished()
48{
49  loop_->assertInLoopThread();
50  assert(state_ == kConnecting);
51  setState(kConnected);
52  channel_->enableReading();
53
54  connectionCallback_(shared_from_this());
55}
56
57void TcpConnection::handleRead()
58{
59  char buf[65536];
60  ssize_t n = read(channel_->fd(), buf, sizeof buf);
61  messageCallback_(shared_from_this(), buf, n);
62  // FIXME: close connection if n == 0
63}
64
65