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 复制代码
相关推荐
Joker 0073 分钟前
Ubuntu上安装FreeSurfer的详细流程
linux·深度学习·ubuntu
默默前行的虫虫24 分钟前
声音触发器。用于自动化场景检测器
运维·自动化
薛定猫AI29 分钟前
【深度解析】从 Claude Mythos 到自进化 Agent:下一代 AI 智能体技术栈与落地实践
网络·人工智能
okra-35 分钟前
什么是接口?
服务器·前端·网络
想你依然心痛1 小时前
从零开始:Mac/Windows/Linux 三系统开发环境配置完全指南
linux·windows·macos
DX_水位流量监测1 小时前
德希科技在线色度传感器
大数据·网络·人工智能·水质监测·水质传感器·水质厂家·农村供水水质监测方案
陳10301 小时前
Linux:第一个系统程序--进度条
linux·运维·服务器
克莱因3581 小时前
Linux 进程(2)服务管理指令
java·linux·服务器
不怕犯错,就怕不做1 小时前
Linux中的IS_ENABLED 函数实战使用demo
linux·驱动开发·嵌入式硬件
Blurpath住宅代理1 小时前
原生住宅IP深度解析:技术本质、优势边界与使用规范
网络·静态ip·动态ip·代理·代理ip·住宅ip·住宅代理