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 复制代码
相关推荐
JoyCheung-12 分钟前
Free底层是怎么释放内存的
linux·c语言
旖旎夜光22 分钟前
Linux(9)
linux·学习
chao_6666662 小时前
解决 PowerShell 中文乱码问题
网络·学习·powershell
喵了meme2 小时前
Linux学习日记24:Linux网络编程基础
linux·网络·学习
whlqjn_12112 小时前
linux下使用SHC对Shell脚本进行封装和源码隐藏
linux·centos
Yan-英杰2 小时前
BoostKit OmniAdaptor 源码深度解析
网络·人工智能·网络协议·tcp/ip·http
weixin_462446233 小时前
K8s 集群部署基础:Linux 三节点 SSH 互信(免密登录)配置指南
linux·kubernetes·ssh
小北方城市网3 小时前
第1课:架构设计核心认知|从0建立架构思维(架构系列入门课)
大数据·网络·数据结构·python·架构·数据库架构
f***24113 小时前
高效自动化管理临时文件的技术方案
运维·自动化
黄焖鸡能干四碗3 小时前
信息安全网络安全评估报告(WORD)
大数据·网络·人工智能·安全·web安全·制造·需求分析