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 复制代码
相关推荐
pengyi871015几秒前
动态IP池快速更换实操方案,5分钟完成IP替换
服务器·网络·tcp/ip
GL_Rain11 分钟前
快速搭建Halo博客 + 崩溃秒恢复方案(Docker极简部署)
运维·docker·容器
不做无法实现的梦~16 分钟前
Linux 上使用 CLion 开发嵌入式,并用 Codex CLI
linux·运维·服务器
张32334 分钟前
Ansible拆分大型Playbook
linux·ansible
平升电子DATA861 小时前
地下管网(污水/雨水管网)流量怎么监测?
网络
被摘下的星星1 小时前
以太网技术
服务器·网络
卓豪终端管理1 小时前
两种终端数据清除策略的技术笔记:企业定向清除 vs 完全擦除
运维·自动化
24zhgjx-lxq2 小时前
OSPF的网络类型:NBMA和P2MP
网络·智能路由器·hcip·ensp·ospf
lulukanshijie2 小时前
Packer 入门:自动化镜像构建工具
运维·其他·自动化
苦逼大学生被编程薄纱2 小时前
Ext 文件系统基础:Linux 存储基石入门(下)
linux·运维·服务器