欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

tcp客户端

程序员文章站 2022-06-05 21:08:11
...
class tcpClient
{
public:
    tcpClient()
    {
        std::cout<<"tcpClient"<<endl;
        sockfd = -1;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd<=0)
        {
            perror("tcpClient socket error: ");
        }
        connectOk = false;
    }
    bool connectToServer(string ip,unsigned short port)
    {
        if(connectOk || sockfd<=0)
        {
            std::cout<<"connectToServer error: "<<ip<<":"<<port<<endl;
            return false;
        }
        int iOption_value = 1;
        setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR|SO_REUSEPORT, (const void *)&iOption_value, sizeof(iOption_value));
        struct sockaddr_in serveraddr;
        memset(&serveraddr,0,sizeof(serveraddr));
        serveraddr.sin_family=AF_INET;
        serveraddr.sin_port=htons(port);
        serveraddr.sin_addr.s_addr = inet_addr(ip.c_str());
        printf("the serveraddr ip is %s, port is %d\n",inet_ntoa(serveraddr.sin_addr),htons(serveraddr.sin_port));
        if(connect(sockfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr))<0)
        {
            perror("connect error");
            connectOk = false;
            return false;
        }
        else
        {
            std::cout<<"connectToServer ok"<<endl;
            connectOk = true;
            return true;
        }
    }
    bool recvData(int fd,char *buf,int len)
    {
        printf("fd=%d buf=%s len=%d\n",fd, buf, len);
    }
    int handle_recv()
    {
        #define MAXBUF 1024
        char buf[MAXBUF + 1];
        int len;
        /* 开始处理每个新连接上的数据收发 */
        bzero(buf, MAXBUF + 1);
        /* 接收客户端的消息 */
        int count = 0;
        while(1)
        {
            if(!connectOk)
            {
                usleep(100000);
                continue;
            }
        	len = recv(sockfd, buf, MAXBUF, 0);
        	if(len > 0)
            {
                recvData(sockfd,buf,len);
        	}
            else
            {
            	if(len < 0)
                {
                	break;
            	}
                else
                {
                	count = -1;
                	break;
            	}
            	
        	}
    	}
        /* 处理每个新连接上的数据收发结束 */
        return count;
    }
    static void *recvThread(void *arg)
    {
        tcpClient *pthis = (tcpClient *)arg;
        if(pthis)
        {
            pthis->handle_recv();
        }
        return pthis;
    }
    void startRecvThread()
    {
        pthread_t thr;
        if(pthread_create(&thr,NULL,recvThread,this)!=0)
        {
            perror("create createThread failed!\n");
            return;
        }
    }
private:
    int sockfd;
    bool connectOk;
};