34muduo_net库源码分析(十)

最新《C++大并发高性能高可用可伸缩性服务器开发教程》 不可多得的教程,而且很少有讲解这部分的课程,需要的就下载吧! -------------课程目录-------------01大并发服务器架构介绍.avi 02大型网站架构演变过程.avi 03poll(一).avi 04poll(二)_.avi 05epoll(一).avi 06epoll(二).avi 07muduo介绍.avi 08面向对象编程风格.avi 09基于对象编程风格.avi 10... 阅读详情

1.连接关闭时序图


2.代码

1.TcpConnection.h

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is a public header file, it must only include public header files.

#ifndef MUDUO_NET_TCPCONNECTION_H
#define MUDUO_NET_TCPCONNECTION_H

#include <muduo/base/Mutex.h>
#include <muduo/base/StringPiece.h>
#include <muduo/base/Types.h>
#include <muduo/net/Callbacks.h>
//#include <muduo/net/Buffer.h>
#include <muduo/net/InetAddress.h>

//#include <boost/any.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>

namespace muduo
{
namespace net
{

class Channel;
class EventLoop;
class Socket;

///
/// TCP connection, for both client and server usage.
///
/// This is an interface class, so don't expose too much details.
class TcpConnection : boost::noncopyable,
                      public boost::enable_shared_from_this<TcpConnection>
{
 public:
  /// Constructs a TcpConnection with a connected sockfd
  ///
  /// User should not create this object.
  TcpConnection(EventLoop* loop,
                const string& name,
                int sockfd,
                const InetAddress& localAddr,
                const InetAddress& peerAddr);
  ~TcpConnection();

  EventLoop* getLoop() const { return loop_; }
  const string& name() const { return name_; }
  const InetAddress& localAddress() { return localAddr_; }
  const InetAddress& peerAddress() { return peerAddr_; }
  bool connected() const { return state_ == kConnected; }

  void setConnectionCallback(const ConnectionCallback& cb)
  { connectionCallback_ = cb; }

  void setMessageCallback(const MessageCallback& cb)
  { messageCallback_ = cb; }

  /// Internal use only.
  void setCloseCallback(const CloseCallback& cb)
  { closeCallback_ = cb; }

  // called when TcpServer accepts a new connection
  void connectEstablished();   // should be called only once
  // called when TcpServer has removed me from its map
  void connectDestroyed();  // should be called only once

 private:
  enum StateE { kDisconnected, kConnecting, kConnected, kDisconnecting };
  void handleRead(Timestamp receiveTime);
  void handleClose();
  void handleError();
  void setState(StateE s) { state_ = s; }

  EventLoop* loop_;			// 所属EventLoop
  string name_;				// 连接名
  StateE state_;  // FIXME: use atomic variable
  // we don't expose those classes to client.
  boost::scoped_ptr<Socket> socket_;
  boost::scoped_ptr<Channel> channel_;
  InetAddress localAddr_;
  InetAddress peerAddr_;
  ConnectionCallback connectionCallback_;
  MessageCallback messageCallback_;
  CloseCallback closeCallback_;
};

typedef boost::shared_ptr<TcpConnection> TcpConnectionPtr;

}
}

#endif  // MUDUO_NET_TCPCONNECTION_H

2.TcpConnection.cc

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/net/TcpConnection.h>

#include <muduo/base/Logging.h>
#include <muduo/net/Channel.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/Socket.h>
#include <muduo/net/SocketsOps.h>

#include <boost/bind.hpp>

#include <errno.h>
#include <stdio.h>

using namespace muduo;
using namespace muduo::net;
/*
void muduo::net::defaultConnectionCallback(const TcpConnectionPtr& conn)
{
  LOG_TRACE << conn->localAddress().toIpPort() << " -> "
            << conn->peerAddress().toIpPort() << " is "
            << (conn->connected() ? "UP" : "DOWN");
}

void muduo::net::defaultMessageCallback(const TcpConnectionPtr&,
                                        Buffer* buf,
                                        Timestamp)
{
  buf->retrieveAll();
}
*/
TcpConnection::TcpConnection(EventLoop* loop,
                             const string& nameArg,
                             int sockfd,
                             const InetAddress& localAddr,
                             const InetAddress& peerAddr)
  : loop_(CHECK_NOTNULL(loop)),
    name_(nameArg),
    state_(kConnecting),
    socket_(new Socket(sockfd)),
    channel_(new Channel(loop, sockfd)),
    localAddr_(localAddr),
    peerAddr_(peerAddr)/*,
    highWaterMark_(64*1024*1024)*/
{
  // 通道可读事件到来的时候,回调TcpConnection::handleRead,_1是事件发生时间
  channel_->setReadCallback(
      boost::bind(&TcpConnection::handleRead, this, _1));
  // 连接关闭,回调TcpConnection::handleClose
  channel_->setCloseCallback(
      boost::bind(&TcpConnection::handleClose, this));
  // 发生错误,回调TcpConnection::handleError
  channel_->setErrorCallback(
      boost::bind(&TcpConnection::handleError, this));
  LOG_DEBUG << "TcpConnection::ctor[" <<  name_ << "] at " << this
            << " fd=" << sockfd;
  socket_->setKeepAlive(true);
}

TcpConnection::~TcpConnection()
{
  LOG_DEBUG << "TcpConnection::dtor[" <<  name_ << "] at " << this
            << " fd=" << channel_->fd();
}

void TcpConnection::connectEstablished()
{
  loop_->assertInLoopThread();
  assert(state_ == kConnecting);
  setState(kConnected);
  LOG_TRACE << "[3] usecount=" << shared_from_this().use_count();
  channel_->tie(shared_from_this());
  channel_->enableReading();	// TcpConnection所对应的通道加入到Poller关注

  connectionCallback_(shared_from_this());
  LOG_TRACE << "[4] usecount=" << shared_from_this().use_count();
}

void TcpConnection::connectDestroyed()
{
  loop_->assertInLoopThread();
  if (state_ == kConnected)
  {
    setState(kDisconnected);
    channel_->disableAll();

    connectionCallback_(shared_from_this());
  }
  channel_->remove();
}

void TcpConnection::handleRead(Timestamp receiveTime)
{
  /*
  loop_->assertInLoopThread();
  int savedErrno = 0;
  ssize_t n = inputBuffer_.readFd(channel_->fd(), &savedErrno);
  if (n > 0)
  {
    messageCallback_(shared_from_this(), &inputBuffer_, receiveTime);
  }
  else if (n == 0)
  {
    handleClose();
  }
  else
  {
    errno = savedErrno;
    LOG_SYSERR << "TcpConnection::handleRead";
    handleError();
  }
  */
  loop_->assertInLoopThread();
  int savedErrno = 0;
  char buf[65536];
  ssize_t n = ::read(channel_->fd(), buf, sizeof buf);
  if (n > 0)
  {
    messageCallback_(shared_from_this(), buf, n);
  }
  else if (n == 0)
  {
    handleClose();
  }
  else
  {
    errno = savedErrno;
    LOG_SYSERR << "TcpConnection::handleRead";
    handleError();
  }
  
}

void TcpConnection::handleClose()
{
  loop_->assertInLoopThread();
  LOG_TRACE << "fd = " << channel_->fd() << " state = " << state_;
  assert(state_ == kConnected || state_ == kDisconnecting);
  // we don't close fd, leave it to dtor, so we can find leaks easily.
  setState(kDisconnected);
  channel_->disableAll();

  TcpConnectionPtr guardThis(shared_from_this());
  connectionCallback_(guardThis);		// 这一行,可以不调用
  LOG_TRACE << "[7] usecount=" << guardThis.use_count();
  // must be the last line
  closeCallback_(guardThis);	// 调用TcpServer::removeConnection
  LOG_TRACE << "[11] usecount=" << guardThis.use_count();
}

void TcpConnection::handleError()
{
  int err = sockets::getSocketError(channel_->fd());
  LOG_ERROR << "TcpConnection::handleError [" << name_
            << "] - SO_ERROR = " << err << " " << strerror_tl(err);
}

3.TcpServer.h

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is a public header file, it must only include public header files.

#ifndef MUDUO_NET_TCPSERVER_H
#define MUDUO_NET_TCPSERVER_H

#include <muduo/base/Types.h>
#include <muduo/net/TcpConnection.h>

#include <map>
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>

namespace muduo
{
namespace net
{

class Acceptor;
class EventLoop;

///
/// TCP server, supports single-threaded and thread-pool models.
///
/// This is an interface class, so don't expose too much details.
class TcpServer : boost::noncopyable
{
 public:
  //typedef boost::function<void(EventLoop*)> ThreadInitCallback;

  //TcpServer(EventLoop* loop, const InetAddress& listenAddr);
  TcpServer(EventLoop* loop,
            const InetAddress& listenAddr,
            const string& nameArg);
  ~TcpServer();  // force out-line dtor, for scoped_ptr members.

  const string& hostport() const { return hostport_; }
  const string& name() const { return name_; }

  /// Starts the server if it's not listenning.
  ///
  /// It's harmless to call it multiple times.
  /// Thread safe.
  void start();

  /// Set connection callback.
  /// Not thread safe.
  // 设置连接到来或者连接关闭回调函数
  void setConnectionCallback(const ConnectionCallback& cb)
  { connectionCallback_ = cb; }

  /// Set message callback.
  /// Not thread safe.
  // 设置消息到来回调函数
  void setMessageCallback(const MessageCallback& cb)
  { messageCallback_ = cb; }


 private:
  /// Not thread safe, but in loop
  void newConnection(int sockfd, const InetAddress& peerAddr);
  /// Thread safe.
  void removeConnection(const TcpConnectionPtr& conn);

  typedef std::map<string, TcpConnectionPtr> ConnectionMap;

  EventLoop* loop_;  // the acceptor loop
  const string hostport_;		// 服务端口
  const string name_;			// 服务名
  boost::scoped_ptr<Acceptor> acceptor_; // avoid revealing Acceptor
  ConnectionCallback connectionCallback_;
  MessageCallback messageCallback_;
  bool started_;
  // always in loop thread
  int nextConnId_;				// 下一个连接ID
  ConnectionMap connections_;	// 连接列表
};

}
}

#endif  // MUDUO_NET_TCPSERVER_H

4.TcpServer.cc

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/net/TcpServer.h>

#include <muduo/base/Logging.h>
#include <muduo/net/Acceptor.h>
#include <muduo/net/EventLoop.h>
//#include <muduo/net/EventLoopThreadPool.h>
#include <muduo/net/SocketsOps.h>

#include <boost/bind.hpp>

#include <stdio.h>  // snprintf

using namespace muduo;
using namespace muduo::net;

TcpServer::TcpServer(EventLoop* loop,
                     const InetAddress& listenAddr,
                     const string& nameArg)
  : loop_(CHECK_NOTNULL(loop)),
    hostport_(listenAddr.toIpPort()),
    name_(nameArg),
    acceptor_(new Acceptor(loop, listenAddr)),
    /*threadPool_(new EventLoopThreadPool(loop)),
    connectionCallback_(defaultConnectionCallback),
    messageCallback_(defaultMessageCallback),*/
    started_(false),
    nextConnId_(1)
{
  // Acceptor::handleRead函数中会回调用TcpServer::newConnection
  // _1对应的是socket文件描述符,_2对应的是对等方的地址(InetAddress)
  acceptor_->setNewConnectionCallback(
      boost::bind(&TcpServer::newConnection, this, _1, _2));
}

TcpServer::~TcpServer()
{
  loop_->assertInLoopThread();
  LOG_TRACE << "TcpServer::~TcpServer [" << name_ << "] destructing";

  for (ConnectionMap::iterator it(connections_.begin());
      it != connections_.end(); ++it)
  {
    TcpConnectionPtr conn = it->second;
    it->second.reset();		// 释放当前所控制的对象,引用计数减一
    conn->getLoop()->runInLoop(
      boost::bind(&TcpConnection::connectDestroyed, conn));
    conn.reset();			// 释放当前所控制的对象,引用计数减一
  }
}

// 该函数多次调用是无害的
// 该函数可以跨线程调用
void TcpServer::start()
{
  if (!started_)
  {
    started_ = true;
  }

  if (!acceptor_->listenning())
  {
	// get_pointer返回原生指针
    loop_->runInLoop(
        boost::bind(&Acceptor::listen, get_pointer(acceptor_)));
  }
}

void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
{
  loop_->assertInLoopThread();
  char buf[32];
  snprintf(buf, sizeof buf, ":%s#%d", hostport_.c_str(), nextConnId_);
  ++nextConnId_;
  string connName = name_ + buf;

  LOG_INFO << "TcpServer::newConnection [" << name_
           << "] - new connection [" << connName
           << "] from " << peerAddr.toIpPort();
  InetAddress localAddr(sockets::getLocalAddr(sockfd));
  // FIXME poll with zero timeout to double confirm the new connection
  // FIXME use make_shared if necessary
  TcpConnectionPtr conn(new TcpConnection(loop_,
                                          connName,
                                          sockfd,
                                          localAddr,
                                          peerAddr));

  LOG_TRACE << "[1] usecount=" << conn.use_count();
  connections_[connName] = conn;
  LOG_TRACE << "[2] usecount=" << conn.use_count();
  conn->setConnectionCallback(connectionCallback_);
  conn->setMessageCallback(messageCallback_);

  conn->setCloseCallback(
      boost::bind(&TcpServer::removeConnection, this, _1));

  conn->connectEstablished();
  LOG_TRACE << "[5] usecount=" << conn.use_count();

}

void TcpServer::removeConnection(const TcpConnectionPtr& conn)
{
  loop_->assertInLoopThread();
  LOG_INFO << "TcpServer::removeConnectionInLoop [" << name_
           << "] - connection " << conn->name();


  LOG_TRACE << "[8] usecount=" << conn.use_count();
  size_t n = connections_.erase(conn->name());
  LOG_TRACE << "[9] usecount=" << conn.use_count();

  (void)n;
  assert(n == 1);
  
  loop_->queueInLoop(
      boost::bind(&TcpConnection::connectDestroyed, conn));
  LOG_TRACE << "[10] usecount=" << conn.use_count();

}

5.Reactor_09.cc

#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/InetAddress.h>

#include <boost/bind.hpp>

#include <stdio.h>

using namespace muduo;
using namespace muduo::net;

class TestServer
{
 public:
  TestServer(EventLoop* loop,
             const InetAddress& listenAddr)
    : loop_(loop),
      server_(loop, listenAddr, "TestServer")
  {
    server_.setConnectionCallback(
        boost::bind(&TestServer::onConnection, this, _1));
    server_.setMessageCallback(
        boost::bind(&TestServer::onMessage, this, _1, _2, _3));
  }

  void start()
  {
	  server_.start();
  }

 private:
  void onConnection(const TcpConnectionPtr& conn)
  {
    if (conn->connected())
    {
      printf("onConnection(): new connection [%s] from %s\n",
             conn->name().c_str(),
             conn->peerAddress().toIpPort().c_str());
    }
    else
    {
      printf("onConnection(): connection [%s] is down\n",
             conn->name().c_str());
    }
  }

  void onMessage(const TcpConnectionPtr& conn,
                   const char* data,
                   ssize_t len)
  {
    printf("onMessage(): received %zd bytes from connection [%s]\n",
           len, conn->name().c_str());
  }

  EventLoop* loop_;
  TcpServer server_;
};


int main()
{
  printf("main(): pid = %d\n", getpid());

  InetAddress listenAddr(8888);
  EventLoop loop;

  TestServer server(&loop, listenAddr);
  server.start();

  loop.loop();
}


Android遇到的问题,解决方法和一些小技巧,kotlin线程安全 解决方法: //我们在Activity中去动态修改背景颜色,就不需要重新再写一个shape了。是不是很方便 GradientDrawable drawable =(GradientDrawable)view.getBackground(); drawable.setColor(getResources().getColor(color)); 2.android studio 创建新项目一直building解决 主要原因,可能是你的Android studio的版本与之对应不上,或者是被墙了。导致下载不.. 阅读详情

相关推荐

灰度重心法实战:从原理到MATLAB代码实现激光条纹中心线提取

本文详细介绍了激光条纹中心线提取的核心方法——灰度重心法。通过物理类比阐释其原理,并提供从图像预处理到MATLAB代码实现的完整实战教程。文章重点解析了算法流程、关键参数调整及常见问题避坑指南,帮助读者快速掌握这一机器视觉与三维测量中的基础且高效的技术。

cake8的博客 468

muduo_net库源码分析(25)

TCP网络编程本质     TCP网络编程最本质是的处理三个半事件         连接建立:服务器accept(被动)接受连接,客户端connect(主动)发起连接         连接断开:主动断开(close、shutdown),被动断开(read返回0)         消息到达:文件描述符可读         消息发送完毕:这算半个。对于低流量的服务,可不必关心这个事件;这里的

Riak, Spark, Golang, Erlang, 云存储, 云计算, 数据挖掘 2462

VSCode+Ai-WB2-12F开发板环境搭建全攻略(附科学上网替代方案)

本文详细介绍了如何在Windows系统上为Ai-WB2-12F开发板搭建本地化VSCode开发环境。通过使用MSYS2国内镜像、获取完整SDK与RISC-V工具链,并配置系统环境变量与VSCode集成终端,手把手指导完成从环境搭建、代码编译到固件烧录的全过程,有效解决了网络依赖问题,提升物联网开发效率。

zzz56的博客 705

muduo_net库源码分析(26-1

Channel是selectable IO channel,负责注册与响应IO 事件,它不拥有file descriptor。 Channel是Acceptor、Connector、EventLoop、TimerQueue、TcpConnection的成员,生命期由后者控制。 时序图 EventLoop头文件 eventl

Riak, Spark, Golang, Erlang, 云存储, 云计算, 数据挖掘 2281

surfer10与Arcgis10.3 完美生成等值线和等值面方法

surfer10 与Arcgis10.3生成等值线和等值面的步骤如下: 1.准备surfer用的Book1.dat文件,格式如下: "x" "y" "z" 116.471992 40.809975 232 116.335556 40.700542 1235 116.541626 40.713333 214 116.73349 40.798607 566 2.在surfer中,选择Gr

哈里·雪利博客 1万+

PCL 点云格式转换【2024最新版】

常见点云格式转化汇总包括txt、stl、csv、ply、obj、xyz、las等。博客长期更新,本文最近一次更新时间为:2024年9月14日,代码更新至PCL1.14.1版本。

点云侠的博客 39万+

net11. 应用层缓冲区类——Buffer

Buffer类 为什么采用non-blocking网络编程中应用层buffer是必需的? non-blockingIO的核心思想是避免阻塞在read()或write()或其他IO系统调用上,这样可以最大限度地复用thread-of-control。让一个线程能服务于多个socket连接。IO线程只能阻塞在IOmultiplexing函数上,如select/poll/epoll_wait。这样一来,应用层的缓冲是必需的,每个TCPsocket都要有stateful的input buffer和output b

TABE_的博客 545

SAP-PLM传输MBOM传输至SAP

BOM 项目文本 (行 2)PLM创建及修改BOM接口。PLM 创建BOM接口抬头。BOM 项目文本(行1)PLM 创建BOM接口抬头。PLM BOM 错误消息。PLM BOM接口组件。组件数量 (BTCI)

qq_32198063的博客 435

30muduo_net库源码分析(六)

1.EventThread (1)任何一个线程,只要创建并运行了EventLoop,都称之为IO线程 (2)IO线程不一定是主线程 (3)muduo并发模型one loop per thread + threadpool (4)为了方便今后使用,定义了EventLoopThread类,该类封装了IO线程 (5)EventLoopThread创建了一个线程 (6)在线程函数中创建了一

INGNIGHT的专栏 419

流体仿真软件:COMSOL Multiphysics二次开发_(3).流体仿真基础理论

流体仿真基础理论包括流体的基本性质、流体运动方程、边界条件、初始条件、湍流模型和网格生成等。在使用COMSOL Multiphysics进行流体仿真时,正确设置这些参数和条件是获得准确仿真结果的关键。通过实际应用案例,可以更好地理解如何在COMSOL中进行流体仿真,并提取和分析仿真结果。希望本文对流体仿真初学者和从业人员有所帮助。

kkchenjj的博客 1349

把大表拆成更好用的“小仓库”:SAP HANA 表分区设计、分区裁剪与内存代价全解析

摘要:本文深入解析SAP HANA分区技术的核心价值与实现策略。作为内存数据库的"手术刀",分区通过将逻辑表横向切分为独立物理容器,显著提升并行计算能力与查询效率。重点探讨了三种分区类型(Range、Hash、Round-robin)的适用场景,以及分区裁剪的优化原理与前提条件。特别指出分区设计需要平衡查询模式与数据分布,并揭示了分区对内存占用的双向影响机制:既可能因字典复制增加消耗,也可能因数据纯度提升压缩率。通过电商订单表等实际案例,展示了合理分区如何将分钟级报表优化至秒级响应。文章

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1657

29muduo_net库源码分析(五)

1.进程(线程)wait/notify (1)pipe (2)socketpair (3)eventfd,eventfd是一个比 pipe更高效的线程间事件通知机制,一方面它比 pipe 少用一个file descripor,节省了资源;另一方面,eventfd的缓冲区管理也简单得多,全部“buffer”只有定长8 bytes,不像 pipe 那样可能有不定长的真正buffer。 in

INGNIGHT的专栏 512

第三篇:NVIDIA cuOpt Python API 详解:LP、QP、MILP 建模与求解,附核心术语名词解释

NVIDIA cuOpt是一款GPU加速的优化求解库,支持LP、QP、MILP和路径优化问题。本文详细介绍了其Python API使用方法,包括核心类Problem的变量定义、约束添加、目标设置和求解配置,并提供了术语解释。cuOpt通过GPU并行计算大幅提升大规模优化问题的求解效率,支持多种求解算法和参数配置,适用于需要高性能计算的优化场景。安装方式包含pip和Docker两种,验证安装后即可快速开始建模求解。

算法工程师 245

muduo_net代码剖析之Acceptor

Acceptor类的简单介绍 类Acceptor用来listen、accept,并调用回调函数来处理新到的连接 构造函数 Acceptor创建非阻塞的listen socket和channel,并且将Acceptor::handleRead函数设置为acceptChannel_的Read Callback Acceptor::Acceptor(EventLoop* loop, const In...

JaweG 272

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

32muduo_net库源码分析(八)

1.Acceptor (1)Acceptor用于accept(2)接受TCP连接 (2)Acceptor的数据成员包括Socket、Channel,Acceptor的socket是listening socket(即serversocket)。Channel用于观察此socket的readable事件,并回调Accptor::handleRead(),后者调用accept(2)来接受新连接

INGNIGHT的专栏 421

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

【muduo】net篇---TcpServer

  TcpServer在创建的过程中,首先new出来自己的核心组件(Acceptor,loop,connectionMap,threadPool)之后TcpServer会向Acceptor注册一个新连接到来时的Connection回调函数。一旦接受到一个client的连接,就会调用TcpServer::newConnection()函数。这个函数使用round-robin算法从EventLoopT...

青萍之末的博客 1144

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

muduo库安装

一、简介 Muduo(木铎)是基于 Reactor 模式的网络库。 二、安装 从github库下载源码安装:https://github.com/chenshuo/muduo muduo依赖了很多的库,所以在安装muduo之前应该安装这些库,包括:curl、c-ares、protobuf。 前面两个在centos6.2可以使用yum安装,protobuf只能源码安装了,参见这篇文章。 ...

weixin_34233679的博客 303

高并发服务器架构笔记(4)——muduo_net 源码分析

TCP 网络编程最本质的是处理3.5个事件1. 连接建立:服务端 accept(被动)接受连接,客户端 connect (主动)发起连接。2.连接断开:主动断开(close、shutdown),被动断开(read 返回0)3 处理消息到达事件(核心):当网络库事件循环中的可读事件触发时,将数据从内核缓冲区移动到应用缓冲区中。调用OnMessage( )函数,根据协议判断数据包是否一个完整的数据包(不

ize 877

muduo网络库学习之muduo_inspect 库涉及到的类

muduo inspect 库通过HTTP方式为服务器提供监控接口, 现在只实现进程相关信息的监控,通过成员ProcessInspector 实现。 ProcessInspector // 通过ProcessInfo返回进程信息      ProcessInfo // 获取进程相关信息 我们可以参照 ProcessInspector 实现一个如TcpStateInspector,作为

Meditation 3921

muduo_net库源码分析(一)

1.TCP网络编程本质 TCP网络编程最本质是的处理三个半事件 1.连接建立:服务器accept(被动)接受连接,客户端connect(主动)发起连接。 2.连接断开:主动断开(close、shutdown),被动断开(read返回0)。 3.消息到达:文件描述符可读。 4.消息发送完毕:这算半个。对于低流量的服务,可不必关心这个事件;这里的发送完毕是指数据写入内核缓冲区,将由TCP协议栈负责数据的发送与重传,不代表对端已经接收到数据。 2.EchoServer类图 显然,这是基于对象的编程思想,在Ec

ShenHang_的博客 358

muduo_net代码剖析之连接器Connector

Connecto、TcpClient

JaweG 425

31muduo_net库源码分析(七)

1.Socket封装 (1)Endian.h  封装了字节序转换函数(全局函数,位于muduo::net::sockets名称空间中)。 (2)SocketsOps.h/ SocketsOps.cc  封装了socket相关系统调用(全局函数,位于muduo::net::sockets名称空间中)。 (3)Socket.h/Socket.cc(Socket类)  用RAII方法封装

INGNIGHT的专栏 510

muduo库net源码分析一(网络编程本质)

TCP网络编程最本质的是处理三个半事件 1、连接建立:服务器accept(被动)接受连接,客户端connect(主动)发起连接。 2、连接断开:主动断开(close、shutdown),被动断开(read返回0)。 3、消息到达:文件描述符可读。 4、消息发送完毕:这算半个。对于低流量的服务,可不必关心这个事件,这里的发送完毕是指数据写入操作系统缓冲区,将由TCP协议栈负责数据的发送与重传,不代表对方已经接收到数据。对于高流量的程序,应用要在发送完毕后再发送,以免数据丢包。 一个套接字有两个缓冲区

侯彩桦 1693

25muduo_net库源码分析(一)

1.TCP网络编程本质 TCP网络编程最本质是的处理三个半事件 (1)连接建立:服务器accept(被动)接受连接,客户端connect(主动)发起连接 (2)连接断开:主动断开(close、shutdown),被动断开(read返回0) (3)消息到达:文件描述符可读 (4)消息发送完毕:这算半个。对于低流量的服务,可不必关心这个事件;这里的发送完毕是指数据写入操作系统缓冲区,将由

INGNIGHT的专栏 483

muduo_net代码剖析之Buffer类的设计

epoll使用level trigger(LT模式)的原因 ① 与poll兼容 ② LT模式不会发生漏掉事件的BUG,但POLLOUT事件不能一开始就关注,否则会出现busy loop,而应该在write无法完全写入内核缓冲区的时候才关注,将未写入内核缓冲区的数据添加到应用层output buffer,直到应用层output buffer写完,写完后停止关注POLLOUT事件 ③ 读写的时候不必等...

JaweG 572

muduo网络库(3):对套接字和监听事件的封装Channel

一、概述 Channel类中实现了: 描述符fd; 需要监听的事件events; fd被激活调用的可读/可写/关闭/错误回调函数; const int fd_; //描述符fd; int events_; //需要监听的事件events; EventCallback readCallback_; ...

李骁睿写技术的地方 341
上一篇: 33muduo_net库源码分析(九)
下一篇: 46muduo库使用示例(五)
INGNIGHT
博客等级 码龄12年 210粉丝 1164原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值