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 复制代码
相关推荐
yuanManGan16 分钟前
走进Linux的世界:初识操作系统(Operator System)
android·linux·运维
i_am_a_div_日积月累_36 分钟前
jenkins打包报错
运维·rust·jenkins·jenkins打包报错
一个处女座的暖男程序猿38 分钟前
2G2核服务器安装ES
服务器·elasticsearch·jenkins
GIOTTO情42 分钟前
舆情处置的自动化实践:基于Infoseek舆情系统的技术解析与落地指南
运维·自动化·linq
Thexhy1 小时前
在 CentOS 7 的 Linux 系统中配置 NFS
linux·运维·学习·centos
咯哦哦哦哦1 小时前
linux vscode+cmake+clangd
linux·ide·vscode
曹天骄1 小时前
Let’s Encrypt 证书申请与多服务器 HTTPS 配置指南
运维·服务器·https
lang201509281 小时前
如何在 Linux 中获取更多信息
linux·运维·服务器
是Yu欸1 小时前
【博资考5】网安2025
网络·人工智能·经验分享·笔记·网络安全·ai·博资考
DeBuggggggg1 小时前
linux 安装Python3.9 且支持SSL
linux·运维·ssl