CsendData

#include "CSendData.h"
#include <string.h>  
#include <stdlib.h>  
#include <stdio.h>  
#include <algorithm>  
#include <fstream>  
#include <iostream>  
#include <errno.h>
#include <assert.h>

#define SEND_RQ(MSG) send(m_socket,MSG,strlen(MSG),0)
#define _DEBUG_PRINT(X) X  
using namespace std;
using std::string; 


#pragma warning(disable:4996)

CSendData::CSendData()
{
    m_socket = -1;
    ez_socket_init();
}

CSendData::~CSendData()
{
    ez_socket_cleanup();

}
int CSendData::HttpDataState()
{
    return m_socket;

}

int  CSendData::HttpSendFileStart(const char *pServerIP, int iServerPort)
{
    if(m_socket > 0)
    {
        printf("CSendData::HttpSendFileStart(): m_socket = %d > 0,need close\r\n",m_socket);        
        HTTP_Close(m_socket);
        m_socket = -1;
    }
    m_ServerIP = pServerIP;
    m_ServerPort = iServerPort;
    m_socket = TcpConnect(pServerIP, iServerPort);
    return m_socket;
}
void CSendData::HttpSendFileStop() //关闭打开的套接字
{
    if( m_socket <= 0)
    {
        printf("http data channel is not open\n");
    }
    else
    {
        HTTP_Close(m_socket);
        m_socket = -1;
    }   
}

int CSendData::TcpConnect(const char *serverip, unsigned short serverport)
{
    en_bool bRet = en_false;
    int iRet = 0;

    if (NULL == serverip )
    {
        return INVALID_SOCKET;
    }
#if 0    
    char ip[16] = {0};
    struct hostent hostbuf;
    struct hostent *host = NULL;
    size_t hstbuflen = 1024;
    char tmphstbuf[1024]={0};
    int res = -1;
    int herr;
    hstbuflen = 1024;

    struct in_addr in_addr;
    if ( inet_aton(serverip, &in_addr) != 0 )
    {
        //host = gethostbyaddr ((char *) &in_addr, 4, AF_INET);
        strncpy(ip, serverip, sizeof(ip) );
    }
    else
    {
        res = gethostbyname_r(serverip, &hostbuf, tmphstbuf, hstbuflen,&host, &herr);
        if(res || host == NULL)
        {
            debugf(" CASTran::TcpConnect():gethostbyname failed:%s\r\n",serverip);
            return INVALID_SOCKET;
        }
        memset(ip, 0, 16);
        Ip2Str(*(unsigned long *)host->h_addr_list[0],ip);
    }
#endif
    int sockfd = ez_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sockfd < 0)
    {
        errorf("CASTran::TcpConnect : get socket fail >>>>>>>>>>>\r\n");

        return INVALID_SOCKET;
    }

    bRet = ez_set_nodelay(sockfd);
    if (false == bRet)
    {
        goto sock_failed;
    }

    bRet = ez_set_nonblock(en_true, sockfd);
    if (false == bRet)
    {
        goto sock_failed;
    }

    debugf("CASTran::TcpConnect(): connect to %s: %d >>>>>>>>>\r\n",serverip, serverport);

    struct sockaddr_in saRemote;
    memset(&saRemote, 0, sizeof(struct sockaddr_in));

    saRemote.sin_port   = htons(serverport);
    saRemote.sin_family = AF_INET;
    saRemote.sin_addr.s_addr = inet_addr(serverip);

    iRet = ez_connect(sockfd, (struct sockaddr *)&saRemote, sizeof(struct sockaddr));

    /*  */
    if (iRet < 0)
    {
        fd_set wds;
        FD_ZERO(&wds);
        FD_SET(sockfd,&wds);
        struct timeval tv;
        tv.tv_sec = 4;
        tv.tv_usec = 0;
        int iRet = select(sockfd + 1, NULL, &wds, NULL, &tv);

        if(iRet>0 && FD_ISSET(sockfd,&wds))
        {
            int len = -1;
            int error = -1;
            len = sizeof(error);

#ifndef WIN32
        getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len);
#else
        getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char *)&error, (int *)&len);
#endif            
            if(error == 0) 
            {    
                /*connect successful*/
                return sockfd;
            }
            else
            {
                goto sock_failed;
            }        
        }
        else
        {
            goto sock_failed;
        }
    }
    else
    {
        /*connect successful*/
        return sockfd;
    }

sock_failed:
    ez_close_socket(&sockfd);
    sockfd = INVALID_SOCKET;
    debugf("CASTran::TcpConnect: Connect Failed >>>>>>>>\r\n");
    return sockfd;
}



int CSendData::SendData(char *data,int iLen)
{
    if( m_socket <= 0)
    {
        printf("CSendData::SendData() m_socket < 0\r\n");
        return HTTP_CONNECT_FAILED;
    }

    struct  timeval timetmp;
    int     ret;
    int     sendlen  = 0;
    int     errCount = 0;

    while(iLen > sendlen)
    {
        timetmp.tv_sec = HTTP_SEND_TIME/1000;
        timetmp.tv_usec = 0;

        fd_set writefd;

        FD_ZERO(&writefd);
        if(m_socket <= 0)
        {
            printf("[CSendData::SendData]http Error \r\n");
            return HTTP_ERROR;
        }
        FD_SET(m_socket, &writefd);
        ret = select(m_socket + 1, NULL, &writefd, NULL, &timetmp);
        if(ret > 0)
        {       
            int iWantSendLen = iLen-sendlen;
            if (iWantSendLen >  4*1024)
            {
                iWantSendLen = 4*1024;
            }
            ret = send(m_socket, data, iWantSendLen, 0);
            HTTP_ASSERT_RETURN( (ret > 0), HTTP_ERROR);      
            sendlen += ret;
            data   += ret;           
        }
        else
        {
            if (errno == EINTR)
            {
               // tracepoint();
                if(errCount ++ < 10)
                {
                    continue;
                }
            }
            //tracepoint();
            printf("[CSendData::SendData] http send time out \r\n");
            return HTTP_SEND_TIMEOUT;
        }
    }

    return 0;
}

int  CSendData::HttpSendJsonData(Json::Value&  table)
{
    /* 根据RFC1867 填充HTTP报文 */
    char*  cHttpHead = new char[CHTTP_HEAD_LENGTH];           /* 填充报文头 */
    std::string sDetailStream = "";

    if(table.size() > 0)
    {
        Json::FastWriter cJsonWriter;
        sDetailStream = cJsonWriter.write(table);
        SMART_PTF("SMART",INFO,"sDetailStream = %s\n",sDetailStream.c_str());
    }

    memset(cHttpHead, 0, sizeof(CHTTP_HEAD_LENGTH));

    char  cHost[128] ;  
    memset(cHost, 0, 128);

    sprintf(cHost, "%s:%d", m_ServerIP.c_str(), m_ServerPort);

    strcat(cHttpHead,"POST ");
    //strcat(cHttpHead,g_ASReg.m_sServerUrl.c_str());
    strcat(cHttpHead,"http://");
    strcat(cHttpHead,cHost);

    if(m_ServerIP.compare("127.0.0.1"))
    {
        strcat(cHttpHead,"/smart/UpLoad");
    }
    else
    {
        strcat(cHttpHead,"/cuAlarm");
    }
    strcat(cHttpHead," HTTP/1.1\r\n");
    strcat(cHttpHead,"Host: ");
    strcat(cHttpHead,cHost);
    strcat(cHttpHead,"\r\n");
    strcat(cHttpHead,"Connection: keep-alive\r\n");


    char cLength[64] ;  
    memset(cLength, 0, 64);
    sprintf(cLength, "%d", (strlen(sDetailStream.c_str()) ));   
    strcat(cHttpHead,"Content-Length: ");
    strcat(cHttpHead,cLength);
    strcat(cHttpHead,"\r\n");
    strcat(cHttpHead,"Content-Type: application/json; charset=utf-8\r\n");
    strcat(cHttpHead,"Accept: */* ");
    strcat(cHttpHead,"\r\n");
    strcat(cHttpHead,"Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3\r\n");
    strcat(cHttpHead,"Accept-Encoding: gzip, deflate\r\n"); 
    strcat(cHttpHead,"Accept-Language: zh-CN,zh;q=0.8\r\n");

    strcat(cHttpHead,"\r\n");
    strcat(cHttpHead,sDetailStream.c_str());
    /* 发送Http 报文头 */
    int iRet = SendData(cHttpHead,strlen(cHttpHead));
    if ( iRet < 0)
    {
        delete[] cHttpHead;
        return iRet;
    }   

    /* 接收收到的response */
    /*这里简单根据收到应答,判断报文对方已经接收完成,socket可以回收*/
    struct timeval timetmp;
    timetmp.tv_sec = 3;
    timetmp.tv_usec = 0;
    fd_set readfd;
    FD_ZERO(&readfd);
    FD_SET(m_socket,&readfd);
    int iSelectRet = select(m_socket + 1,&readfd,NULL,NULL,&timetmp);
    if(iSelectRet > 0 && FD_ISSET(m_socket,&readfd) )
    {
        char sLoginRecvBuf[1024] = {0,};
        recv(m_socket,sLoginRecvBuf,sizeof(sLoginRecvBuf)-1,0);
        SMART_PTF("SMART", INFO, "sLoginRecvBuf = %s\r\n", sLoginRecvBuf);
    }
    else
    {
        printf("CSendData::HttpSendJsonData():recv ack time out\r\n");
    }
    delete[] cHttpHead;

    return 0;  

}

int  CSendData::HttpSendJsonData( char *buf, int buflen, Json::Value&  table, char *uploadfilename, int iChannelId, int iType)
{
    /* 根据RFC1867 填充HTTP报文 */
    char  cHttpHead[512];           /* 填充报文头 */
    char  cHttpBody[512];           /* 填充报文的body数据 */
    char  cHttpContentImg[512];     /* 填充Img数据 */
    char  cHttpContentDev[512];     /* 填充设备ID */
    char  cHttpContentChann[512];   /* 填充Channel ID */
    char  cHttpContentType[512];    /* 填充Type信息 */
    char  filename[128];            /* 图片文件的名字 */
    char  cFileDetail[512];  
    char  cHttpContentDomain[512];  /* 填充域名 */
    std::string sDetailStream = "";
    static int   iDomainId = 1;

    //struct tm stTime;
    //GetCurrentTime(&stTime);
    //stTime
    char cHttpContentTime[512];     /* 填充设备时间 */
    char cTime[128];
    memset(cTime, 0, 128);
    //sprintf(cTime, "%04d-%02d-%02d %02d:%02d:%02d",stTime.year,stTime.month,stTime.day,stTime.hour,stTime.minute,stTime.second);
    sprintf(cTime, "%04d-%02d-%02d %02d:%02d:%02d",2018,12,12,12,12,60);

    if(table.size() > 0)
    {
        Json::FastWriter cJsonWriter;
       sDetailStream = cJsonWriter.write(table);
    }

    //std::string sDevId = CConifgRegServer::getLatest().deviceID;
    std::string sDevId = "xxxxxxxxx";
    memset(cHttpHead, 0, 512);
    memset(cHttpBody, 0, 512);
    memset(cHttpContentImg, 0, 512);
    memset(cHttpContentDev, 0, 512);
    memset(cHttpContentChann, 0, 512);
    memset(cHttpContentType, 0, 512);   
    memset(filename, 0, 128);
    memset(cFileDetail, 0, 512);
    memset(cHttpContentTime, 0, 512);
    memset(cHttpContentDomain, 0, 512);

    strcpy(filename,uploadfilename);
    strcat(cHttpBody, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cHttpBody, "Content-Disposition: form-data; name=\"imgFiles\"; filename=\"");
    strcat(cHttpBody, filename);
    strcat(cHttpBody, "\"\r\n");
    strcat(cHttpBody, "Content-Type: image/jpeg\r\n\r\n");  

    strcat(cHttpContentImg, "\r\n");
    strcat(cHttpContentImg, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cHttpContentImg, "Content-Disposition: form-data; name=\"imgFiles\"");
    strcat(cHttpContentImg, "\r\n\r\n");
    strcat(cHttpContentImg, "undefined\r\n");

    strcat(cHttpContentDev, "\r\n");
    strcat(cHttpContentDev, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cHttpContentDev, "Content-Disposition: form-data; name=\"deviceid\"");
    strcat(cHttpContentDev, "\r\n\r\n");
    strcat(cHttpContentDev, sDevId.c_str());


    char cChannelId[64];
    memset(cChannelId, 0,64);
    sprintf(cChannelId, "%d", iChannelId);
    strcat(cHttpContentChann, "\r\n");
    strcat(cHttpContentChann, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cHttpContentChann, "Content-Disposition: form-data; name=\"channelid\"");
    strcat(cHttpContentChann, "\r\n\r\n");
    strcat(cHttpContentChann, cChannelId);
    strcat(cHttpContentChann, "\r\n");

    char cType[64];
    memset(cType, 0, 64);
    sprintf(cType, "%d",iType);
    //strcat(cHttpContentType, "\r\n");
    strcat(cHttpContentType, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cHttpContentType, "Content-Disposition: form-data; name=\"type\"");
    strcat(cHttpContentType, "\r\n\r\n");
    strcat(cHttpContentType, cType);
    strcat(cHttpContentType, "\r\n");

    //strcat(cFileDetail, "\r\n");
    strcat(cFileDetail, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cFileDetail, "Content-Disposition: form-data; name=\"detail\"");
    strcat(cFileDetail, "\r\n\r\n");
    strcat(cFileDetail, sDetailStream.c_str());
    strcat(cFileDetail, "\r\n");

    strcat(cHttpContentTime, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cHttpContentTime, "Content-Disposition: form-data; name=\"datetime\"");
    strcat(cHttpContentTime, "\r\n\r\n");
    strcat(cHttpContentTime, cTime);
    strcat(cHttpContentTime, "\r\n");

    char cDomain[64];
    memset(cDomain, 0, 64);
    sprintf(cDomain, "%d", iDomainId);
    strcat(cHttpContentDomain, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cHttpContentDomain, "Content-Disposition: form-data; name=\"domain\"");
    strcat(cHttpContentDomain, "\r\n\r\n");
    strcat(cHttpContentDomain, cDomain);
    strcat(cHttpContentDomain, "\r\n");

    char   content_end[128];
    memset(content_end, 0, 128);
    //strcat(content_end, "\r\n\r\n");
    strcat(content_end, "------WebKitFormBoundaryVCGP1Wsm5vrDMCRs--");
    strcat(content_end, "\r\n");    

    char  cHost[128] ;  
    memset(cHost, 0, 128);
    //sprintf(cHost, "%s:%d", g_ASReg.m_sServerIp.c_str(), g_ASReg.m_iServerPort);
    sprintf(cHost, "%s:%d", "127.0.0.1", 20030);
    strcat(cHttpHead,"POST ");
    //strcat(cHttpHead,g_ASReg.m_sServerUrl.c_str());
    strcat(cHttpHead,"127.0.0.1");
    strcat(cHttpHead," HTTP/1.1\r\n");
    strcat(cHttpHead,"Host: ");
    strcat(cHttpHead,cHost);
    strcat(cHttpHead,"\r\n");
    strcat(cHttpHead,"Connection: keep-alive\r\n");


    char    cLength[64] ;  
    memset(cLength, 0, 64);
    sprintf(cLength, "%d", (buflen+strlen(cHttpBody) + strlen(content_end) + strlen(cHttpContentImg) +
                            strlen(cHttpContentDev) + strlen(cHttpContentChann) + strlen(cHttpContentType) + 
                            strlen(cFileDetail) + strlen(cHttpContentTime) + strlen(cHttpContentDomain) ));   
    strcat(cHttpHead,"Content-Length: ");
    strcat(cHttpHead,cLength);
    strcat(cHttpHead,"\r\n");
    strcat(cHttpHead,"Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryVCGP1Wsm5vrDMCRs\r\n");
    strcat(cHttpHead,"Accept: */* ");
    strcat(cHttpHead,"\r\n");
    strcat(cHttpHead,"Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3\r\n");
    strcat(cHttpHead,"Accept-Encoding: gzip, deflate\r\n"); 
    strcat(cHttpHead,"Accept-Language: zh-CN,zh;q=0.8\r\n");

    /* 发送Http 报文头 */
    int iRet = SendData(cHttpHead,strlen(cHttpHead));
    if ( iRet < 0)
    {
        return iRet;
    }   


    /* 发送报文Body */
    iRet = SendData(cHttpContentImg,strlen(cHttpContentImg));
    if ( iRet < 0)
    {
        return iRet;
    }   
    //_DEBUG_PRINT(cout<<cHttpContentImg);

    iRet = SendData(cHttpBody,strlen(cHttpBody));
    if ( iRet < 0)
    {
        return iRet;
    }   

    /* 发送图片数据*/  
    iRet = SendData(buf,buflen);
    if ( iRet < 0)
    {
       return iRet;
    }   

    iRet = SendData(cHttpContentDev,strlen(cHttpContentDev));
    if ( iRet < 0)
    {
        return iRet;
    }   
    iRet = SendData(cHttpContentChann,strlen(cHttpContentChann));
    if ( iRet < 0)
    {
        return iRet;
    }   

    iRet = SendData(cHttpContentType,strlen(cHttpContentType));
    if ( iRet < 0)
    {
        return iRet;
    }   

    iRet = SendData(cFileDetail,strlen(cFileDetail));
    if ( iRet < 0)
    {
        return iRet;
    }   
    iRet = SendData(cHttpContentTime,strlen(cHttpContentTime));
    if ( iRet < 0 )
    {
        return iRet;
    }
    iRet = SendData(cHttpContentDomain,strlen(cHttpContentDomain));
    if ( iRet < 0 )
    {
        return iRet;
    }
    iRet = SendData(content_end,strlen(content_end));
    if ( iRet < 0)
    {
        return iRet;
    }

    /* 接收收到的response */
    /*这里简单根据收到应答,判断报文对方已经接收完成,socket可以回收*/
    struct timeval timetmp;
    timetmp.tv_sec = 3;
    timetmp.tv_usec = 0;
    fd_set readfd;
    FD_ZERO(&readfd);
    FD_SET(m_socket,&readfd);
    int iSelectRet = select(m_socket + 1,&readfd,NULL,NULL,&timetmp);
    if(iSelectRet > 0 && FD_ISSET(m_socket,&readfd) )
    {
        char sLoginRecvBuf[1024] = {0,};
        recv(m_socket,sLoginRecvBuf,sizeof(sLoginRecvBuf)-1,0);
        printf("sLoginRecvBuf = %s\r\n",sLoginRecvBuf);
    }
    else
    {
        printf("CSendData::HttpSendFileData():recv ack time out\r\n");
    }

    return 0;  

}

int  CSendData::GetSocketVul()
{
return m_socket;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值