• Linux多线程网络通信


    思路:主线程(只有一个)建立连接,就创建子线程。子线程开始通信。
    在这里插入图片描述共享资源:全局数据区,堆区,内核区描述符。
    线程同步不同步需要取决于线程对共享资源区的数据的操作,如果是只读就不需要,如果是写就需要了。

    多线程布置过程

    (1)包含对应的头文件,特别是多线程库文件pthread.h

    #include 
    #include 
    #include 
    #include 
    #include 
    #include //多线程的头文件
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    (2)创建监听套接字

        // 1. 创建监听的套接字  https://subingwen.cn/linux/socket/。返回的是文件描述符
        int lfd = socket(AF_INET, SOCK_STREAM, 0);
        if(lfd == -1)
        {
            perror("socket");
            exit(0);
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    (3)端口绑定

    使用 struct sockaddr_in 类型的结构体来存储数据,需要注意的是大小端转换,因为网络通信使用大端序,需要htons()函数进行端口转换。端口设置完毕之后,可以设置ip地址,我们使用INADDR_ANY,表示任意绑定。

      struct sockaddr_in addr;
        addr.sin_family = AF_INET;//地址族协议
        addr.sin_port = htons(10000);   // 大端端口,要使用的是大端端口,如果是字符串的大小端转换使用其他函数
        // INADDR_ANY代表本机的所有IP, 假设有三个网卡就有三个IP地址
        // 这个宏可以代表任意一个IP地址
        // 这个宏一般用于本地的绑定操作
        addr.sin_addr.s_addr = INADDR_ANY;  // 这个宏的值为0 == 0.0.0.0
        int ret = bind(lfd, (struct sockaddr*)&addr, sizeof(addr));//使用强制类型转换
        if(ret == -1)
        {
            perror("bind");
            exit(0);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    (4)设置监听

        // 3. 设置监听
        ret = listen(lfd, 128);//最多128个
        if(ret == -1)
        {
            perror("listen");
            exit(0);
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    (5)开始通信
    因为我们要实现多线程并发,需要存储多个addr 和fd通信套接字。不是监听套接字。

    struct SockInfo
    {
       struct sockaddr_in addr;//地址信息
       int fd;//文件描述符           
    };
    
    struct SockInfo infos[512];//最多接收256个客户端
    
    
    ----------------------------------------
    对结构体进行初始化,通信描述符设置为-1是为了判断其有没有被占有
    */
    
    // 等待并接受客户端的连接请求, 建立新的连接, 会得到一个新的文件描述符(通信的)		
    int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
    参数:
    sockfd: 监听的文件描述符
    addr: 传出参数, 里边存储了建立连接的客户端的地址信息
    addrlen: 传入传出参数,用于存储addr指向的内存大小
    返回值:函数调用成功,得到一个文件描述符, 用于和建立连接的这个客户端通信,调用失败返回 -1
    */
       //初始化结构体大小
        int max=sizeof(infos)/sizeof(infos[0]);
        for(int i=0;i<max;++i)
        {
            memset(&infos[i],0,max);//将结构体全部设置为0
            infos[i].fd=-1;//通信描述符设置为-1
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    (6)初始化完毕之后需要开始进行进行通信操作


    int clilen = sizeof(struct sockaddr_in);
    
    • 1

    定义一个结构体指针,如果通信套接字fd=-1的话,说明没有被占有,因为如果占用了就会返回fd套接字,失败才返回-1.
    所以如果-1的话,就令这个指针指向一个info数组元素。

            struct SockInfo* pinfo;//结构体指针
            for(int i=0;i<max;++i)
            {
                if(infos[i].fd==-1)
                {
                    pinfo=&infos[i];
                    break;
                }
            }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    开始进行accept(),如果成功了就开辟子线程,把参数pinfo指针指向的内存数据传递给子线程,其实就是对应IP地址,端口,通信协议等数据。

    int cfd = accept(lfd, (struct sockaddr*)&pinfo->addr, &clilen);//并且是个阻塞函数
            pinfo->fd=cfd;
            if(cfd == -1)
            {
                perror("accept");
                break;
    
            }
            //如果连接已经成功了我们需要创建一个子线程,来处理这个客户端连接的数据
            pthread_t tid;
            pthread_create(&tid,NULL,working,pinfo);//通过pinfo指针变量传递数据给子线程
            pthread_detach(tid);//避免阻塞在这里,使用线程分离
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    主线程结束了说明通信服务器已经关闭,close监听套接字。


    close(lfd);//监听的文件描述符,通信的不需要关闭,因为子线程需要使用


    (7)子线程就是对数据的读取操作了。

    //子线程函数
    void* working(void* arg)
    {   
        struct SockInfo*pinfo=(struct SockInfo*)arg;
    
        // 打印客户端的地址信息
        char ip[24] = {0};
        printf("客户端的IP地址: %s, 端口: %d\n",
               inet_ntop(AF_INET, &pinfo->addr.sin_addr.s_addr, ip, sizeof(ip)),
               ntohs(pinfo->addr.sin_port));
    
        // 5. 和客户端通信
        while(1)
        {
            // 接收数据
            char buf[1024];
            memset(buf, 0, sizeof(buf));
            int len = read(pinfo->fd, buf, sizeof(buf));//阻塞函数,cfd是通信的文件描述符accept的函数返回值
            if(len > 0)
            {
                printf("客户端say: %s\n", buf);
                write(pinfo->fd, buf, len);//发送数据的函数
            }
            else if(len  == 0)
            {
                printf("客户端断开了连接...\n");
                break;
            }
            else
            {
                perror("read");
                break;
            }
        }
    
        close(pinfo->fd);
        pinfo->fd=-1;
        return 0;
    }
      
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    全部代码,server_muti

    // server_muti.c
    #include 
    #include 
    #include 
    #include 
    #include 
    #include //多线程的头文件
    
    
    
    void* working(void*arg);
    struct SockInfo
    {
       struct sockaddr_in addr;//地址信息
       int fd;//文件描述符           
    };
    
    struct SockInfo infos[512];
    
    int main()
    {
        // 1. 创建监听的套接字  https://subingwen.cn/linux/socket/。返回的是文件描述符
        int lfd = socket(AF_INET, SOCK_STREAM, 0);
        if(lfd == -1)
        {
            perror("socket");
            exit(0);
        }
    
        // 2. 将socket()返回值和本地的IP端口绑定到一起
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;//地址族协议
        addr.sin_port = htons(10000);   // 大端端口,要使用的是大端端口,如果是字符串的大小端转换使用其他函数
        // INADDR_ANY代表本机的所有IP, 假设有三个网卡就有三个IP地址
        // 这个宏可以代表任意一个IP地址
        // 这个宏一般用于本地的绑定操作
        addr.sin_addr.s_addr = INADDR_ANY;  // 这个宏的值为0 == 0.0.0.0
        int ret = bind(lfd, (struct sockaddr*)&addr, sizeof(addr));//使用强制类型转换
        if(ret == -1)
        {
            perror("bind");
            exit(0);
        }
    
        // 3. 设置监听
        ret = listen(lfd, 128);
        if(ret == -1)
        {
            perror("listen");
            exit(0);
        }
    
    
       //初始化结构体大小
        int max=sizeof(infos)/sizeof(infos[0]);
        for(int i=0;i<max;++i)
        {
            memset(&infos[i],0,max);//将结构体全部设置为0
            infos[i].fd=-1;//通信描述符设置为-1
        }
    
    
        // 4. 阻塞等待并接受客户端连接
        //struct sockaddr_in cliaddr;
        int clilen = sizeof(struct sockaddr_in);
        while(1)
        {   
    
            struct SockInfo* pinfo;//结构体指针
            for(int i=0;i<max;++i)
            {
                if(infos[i].fd==-1)
                {
                    pinfo=&infos[i];
                    break;
                }
            }
    
            int cfd = accept(lfd, (struct sockaddr*)&pinfo->addr, &clilen);//并且是个阻塞函数
            pinfo->fd=cfd;
            if(cfd == -1)
            {
                perror("accept");
                break;
    
            }
            //如果连接已经成功了我们需要创建一个子线程,来处理这个客户端连接的数据
            pthread_t tid;
            pthread_create(&tid,NULL,working,pinfo);//通过pinfo指针变量传递数据给子线程
            pthread_detach(tid);//避免阻塞在这里,使用线程分离
    
        }
        close(lfd);//监听的文件描述符,通信的不需要关闭,因为子线程需要使用
    
    
    
     
    
        return 0;
    }
    
    
    
    //子线程函数
    void* working(void* arg)
    {   
        struct SockInfo*pinfo=(struct SockInfo*)arg;
    
        // 打印客户端的地址信息
        char ip[24] = {0};
        printf("客户端的IP地址: %s, 端口: %d\n",
               inet_ntop(AF_INET, &pinfo->addr.sin_addr.s_addr, ip, sizeof(ip)),
               ntohs(pinfo->addr.sin_port));
    
        // 5. 和客户端通信
        while(1)
        {
            // 接收数据
            char buf[1024];
            memset(buf, 0, sizeof(buf));
            int len = read(pinfo->fd, buf, sizeof(buf));//阻塞函数,cfd是通信的文件描述符accept的函数返回值
            if(len > 0)
            {
                printf("客户端say: %s\n", buf);
                write(pinfo->fd, buf, len);//发送数据的函数
            }
            else if(len  == 0)
            {
                printf("客户端断开了连接...\n");
                break;
            }
            else
            {
                perror("read");
                break;
            }
        }
    
        close(pinfo->fd);
        pinfo->fd=-1;
        return 0;
    }
      
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143

    client.c

    // client.c
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        // 1. 创建通信的套接字
        int fd = socket(AF_INET, SOCK_STREAM, 0);
        if(fd == -1)
        {
            perror("socket");
            exit(0);
        }
    
        // 2. 连接服务器
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(10000);   // 大端端口
        inet_pton(AF_INET, "你的地址", &addr.sin_addr.s_addr);
    
        int ret = connect(fd, (struct sockaddr*)&addr, sizeof(addr));
        if(ret == -1)
        {
            perror("connect");
            exit(0);
        }
    
        // 3. 和服务器端通信
        int number = 0;
        while(1)
        {
            // 发送数据
            char buf[1024];
            sprintf(buf, "你好, 服务器...%d\n", number++);
            write(fd, buf, strlen(buf)+1);
            
            // 接收数据
            memset(buf, 0, sizeof(buf));
            int len = read(fd, buf, sizeof(buf));
            if(len > 0)
            {
                printf("服务器say: %s\n", buf);
            }
            else if(len  == 0)
            {
                printf("服务器断开了连接...\n");
                break;
            }
            else
            {
                perror("read");
                break;
            }
            sleep(1);   // 每隔1s发送一条数据
        }
    
        close(fd);
    
        return 0;
    }
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    这里借鉴了爱编程的大丙博主的程序。
    套接字通信
    Linux多线程多进程编程

  • 相关阅读:
    Linux下uboot添加自定义命令(详细)实例及原理解析
    Tomcat 下载安装与配置
    [TS 类型体操] 初体验之Pick 与 Omit
    Echarts仪表盘3.0
    vue中报 TypeError: Assignment to constant variable.
    面试系列Redis:缓存穿透、击穿、雪崩的解决方案
    asp.net core、c#关于路径的总结
    vue3中使用vue-i18n(ts中使用$t, vue3不用this)
    python curl2pyreqs 生成接口脚本
    python机器学习 一元线性回归 梯度下降法的实现 【Python机器学习系列(四)】
  • 原文地址:https://blog.csdn.net/m0_49586319/article/details/133580156