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 复制代码
相关推荐
zjun10014 分钟前
TCP专栏-1.TCP协议概念说明
网络·网络协议·tcp/ip
yipiantian7 分钟前
在Claude项目中实现跨目录访问Skills
linux·运维·服务器
Agent产品评测局21 分钟前
生产排期与MES/ERP系统打通,实操方法详解 —— 2026企业级智能体自动化选型与实战指南
java·运维·人工智能·ai·chatgpt·自动化
cen__y23 分钟前
Linux07(信号01)
linux·运维·服务器·c语言·开发语言
MT5开发32 分钟前
Linux安装MariaDB
linux·运维·mariadb
德迅云安全杨德俊42 分钟前
DDoS 解析与防御体系
网络·安全·web安全·ddos
国科安芯1 小时前
商业航天电机控制领域抗辐射 MCU 芯片应用研究
网络·单片机·嵌入式硬件·安全性测试
Lentou1 小时前
日志轮询策略
linux·服务器·网络
星融元asterfusion1 小时前
如何为您的网络选择正确的PTP配置文件:一份实用指南
网络·ptp·时间同步
Yoyo25年秋招冲冲冲1 小时前
【亲测可用】ubuntu系统下安装Openclaw+配置飞书
linux·ubuntu·ai·飞书·openclaw