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 复制代码
相关推荐
焱焱枫26 分钟前
Linux疑难杂症诊断利器:深入解析 fuser 命令
linux·运维·服务器
我也要当昏君26 分钟前
6.5 万维网(答案见原书P294)
网络
Andya_net37 分钟前
Java | 基于redis实现分布式批量设置各个数据中心的服务器配置方案设计和代码实践
java·服务器·分布式
博语小屋1 小时前
Linux进程信号(壹)_产生信号
linux·运维·服务器
嶔某1 小时前
网络:传输层协议UDP和TCP
网络·tcp/ip·udp
元亓亓亓1 小时前
考研408--计算机网络--day1-概念&组成功能&三种交换技术&分类
服务器·计算机网络·考研
轻松Ai享生活1 小时前
【Linux】VFS 虚拟文件系统 详解
linux
LCG元1 小时前
Linux环境Python生态速建指南:包管理+虚拟隔离+深度调优
linux
文火冰糖的硅基工坊1 小时前
[嵌入式系统-154]:各种工业现场总线比较
网络·自动驾驶·硬件架构
大白的编程日记.1 小时前
【Linux学习笔记】线程同步与互斥之生产者消费者模型
linux·笔记·学习