Linux知识点 -- 回调函数类型

Linux知识点 -- 回调函数类型

文章目录


1.

cpp 复制代码
#include <functional>

typedef std::function<void (int, const std::string&, const uint16_t&, const std::string&)> func_t;

static void service(int sock, const std::string &cli_ip,
                    const uint16_t &cli_port, const std::string &thread_name)
{
    // 读取消息:TCP流式套接字可以直接使用read和write接口(recvfrom专用于UDP数据报读取)

    char buffer[1024];
    while (true)
    {
        ssize_t s = read(sock, buffer, sizeof(buffer - 1));
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << thread_name << "|" <<  cli_ip << ":" << cli_port << "# " << buffer << std::endl;
        }
        else if (s == 0) // 对端关闭连接
        {
            logMessage(NORMAL, "%s:%d shutdown, me too!", cli_ip.c_str(), cli_port);
            break;
        }
        else
        {
            logMessage(ERROR, "read sock error, %d:%s", errno, strerror(errno));
            break;
        }
        write(sock, buffer, strlen(buffer));
    }
    close(sock); // 线程在回调函数中关闭不用的文件描述符
}

int main()
{
	func_t func = service;
	int sock;
    std::string ip;
    uint16_t port;
	std::string name;
	
	//...初始化参数
	
	func(sock, ip, port, name);
	
	return 0;
}

2.

与上面的写法是等价的;

cpp 复制代码
#include <functional>

using func_t = std::function<void (int, const std::string&, const uint16_t&, const std::string&)>;

3.bind绑定参数

见Reactor服务器

cpp 复制代码
相关推荐
小O_好好学10 分钟前
CentOS 7文件系统
linux·运维·centos
哲伦贼稳妥33 分钟前
一天认识一个硬件之机房地板
运维·网络·经验分享·其他
john_hjy40 分钟前
11. 异步编程
运维·服务器·javascript
x晕x43 分钟前
Linux dlsym符号查找疑惑分析
linux·运维·服务器
活跃的煤矿打工人1 小时前
【星海saul随笔】Ubuntu基础知识
linux·运维·ubuntu
hgdlip2 小时前
如何快速切换电脑的ip地址
网络·tcp/ip·电脑
北京智和信通2 小时前
云平台和虚拟化智慧运维监控,全面提升故障感知与处置能力
运维·虚拟化·云平台·虚拟机监控
fasewer2 小时前
第五章 linux实战-挖矿 二
linux·运维·服务器
楚灵魈2 小时前
[Linux]从零开始的网站搭建教程
linux·运维·服务器
小小不董3 小时前
《Linux从小白到高手》理论篇:深入理解Linux的网络管理
linux·运维·服务器·数据库·php·dba