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 复制代码
相关推荐
猿码优创16 分钟前
过滤境外ip和域名访问的解决方案
网络·网络协议·tcp/ip·安全·阿里云
视觉震撼1 小时前
逐步指南:为大模型构建自动化知识图谱
运维·自动化·知识图谱
yeflx2 小时前
OpenMVS源码编译
运维
code bean2 小时前
深入理解:NO_PROXY 如何绕过代理
网络·代理
有泽改之_2 小时前
ssh命令使用
linux·运维·ssh
lkbhua莱克瓦242 小时前
深入理解HTTP协议:从理论到SpringBoot实践
网络·笔记·后端·网络协议·http·javaweb
华硕之声2 小时前
苏式废土美学游戏
网络·数据·华硕
@@123456胡斌2 小时前
渗透文件内容
网络
玩大数据的龙威2 小时前
【乱占耕地建房】—试点工作平台自动化填报系统
运维·自动化
梁洪飞3 小时前
noc 片上网络
linux·arm开发·嵌入式硬件·arm