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 复制代码
相关推荐
007php007几秒前
服务器上PHP环境安装与更新版本和扩展(安装PHP、Nginx、Redis、Swoole和OPcache)
运维·服务器·后端·nginx·golang·测试用例·php
Fireworkitte2 小时前
gRPC和http长轮询
网络·网络协议·http
LuLaLuLaLeLLLLLL3 小时前
RPC 框架学习笔记
网络·网络协议·rpc
冰橙子id3 小时前
linux-远程访问管理(sshd,scp,sftp)
linux·网络·ssh
光电的一只菜鸡4 小时前
ubuntu之坑(十五)——设备树
linux·数据库·ubuntu
saynaihe6 小时前
ubuntu 22.04 anaconda comfyui安装
linux·运维·服务器·ubuntu
企鹅与蟒蛇6 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
小蜜蜂爱编程6 小时前
ubuntu透网方案
运维·服务器·ubuntu
程序设计实验室7 小时前
小心误关了NAS服务器!修改Linux的电源键功能
linux·nas
AI视觉网奇7 小时前
git 访问 github
运维·开发语言·docker