TCP服务器并发编程

这里写目录标题

1,多线程TCP并发控制

基于多线程的TCP服务器并发程序

javascript 复制代码
#include <iostream>
#include <netinet/in.h>
#include <vector>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/time.h>
#include <cstring>
#include <sys/select.h>
#include<pthread.h>

using namespace std;

#define PORT 8080
#define MAX_CLIENTS 20
#define BUFFER_SIZE 1024
#define MAX  512

struct SockInfo
{
    struct  sockaddr_in  addr;
    int fd;
};

struct  SockInfo  infos[512];

void* working(void* arg);

void* working(void* arg)
{
    struct SockInfo* pinfo = (struct SockInfo*)arg;
    char ip[32];
    //inet_ntop(AF_INET,&pinfo->addr.sin_addr.s_addr,ip,sizeof(ip));
    //ntohs(pinfo->addr.sin_port);

    while(true)
    {
        char buffer[1024];
        int len = recv(pinfo->fd,buffer,sizeof(buffer),0);
        if(len > 0)
        {
            cout<<buffer<<endl;
        }
        else if(len == 0)
        {
            cout<<"客户端已经断开连接"<<endl;
            break;
        }
        else
        {
            break;
        }
    }

}


int  main()
{
    

int serverfd = socket(AF_INET,SOCK_STREAM,0);

    sockaddr_in addr;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(PORT);
    addr.sin_family = AF_INET;
    
    socklen_t len = sizeof(addr);
    bind(serverfd,(sockaddr*)&addr,len);

    listen(serverfd,MAX_CLIENTS);

    

    for(int i = 0;i<MAX;i++)
    {
        infos[i].fd = -1;
    }

    while(true)
    {
        struct  SockInfo* pinfo;
        for(int i = 0;i<MAX;i++)
        {
            if(infos[i].fd == -1)
            { 
               pinfo = &infos[i];
               break;
            }
        }

        socklen_t tmplen = sizeof(pinfo->addr);
        int cfd = accept(serverfd,(struct sockaddr*)&pinfo->addr,&tmplen);
        if(cfd == -1)
        {
            perror("accept");
            continue;
        }

        pinfo->fd = cfd;
    
        //创建子线程
        pthread_t  tid;
        pthread_create(&tid,NULL,working,pinfo);
        pthread_detach(tid);

    }

    close(serverfd);

}
相关推荐
有谁看见我的剑了?7 分钟前
linux 添加硬盘后系统识别不到硬盘处理
linux·运维·服务器
金色光环2 小时前
FreeModbus释放底层的 TCP 监听端口
服务器·网络·tcp/ip
发光小北4 小时前
Modbus TCP 转 Profibus DP 网关如何应用?
网络协议
灰子学技术4 小时前
Envoy HTTP 过滤器处理技术文档
网络·网络协议·http
2401_873479406 小时前
企业安全团队如何配合公安协查?IP查询在电子取证中的技术实践
tcp/ip·安全·网络安全·php
乌托邦的逃亡者6 小时前
Linux中如何检测IP冲突
linux·运维·tcp/ip
一曦的后花园6 小时前
linux搭建promethes并对接node-exporter指标
linux·运维·服务器
乌托邦的逃亡者7 小时前
CentOS/Openeuler主机中,为一个网卡设置多个IP地址
linux·运维·网络·tcp/ip·centos
刘马想放假7 小时前
GRE 隧道深度解析:从协议原理到生产实践
网络协议·安全