美文网首页
CCommunicat

CCommunicat

作者: 冰冰凉3 | 来源:发表于2019-10-24 21:55 被阅读0次

    TCPcommunicat.h

    // TCPcommunicat.h: interface for the CTCPcommunicat class.
    //
    //////////////////////////////////////////////////////////////////////
    
    #if !defined(AFX_TCPCOMMUNICAT_H__F903C55C_4E75_4F30_BFC3_D44A969C6C2D__INCLUDED_)
    #define AFX_TCPCOMMUNICAT_H__F903C55C_4E75_4F30_BFC3_D44A969C6C2D__INCLUDED_
    
    #if _MSC_VER > 1000
    #pragma once
    #endif // _MSC_VER > 1000
    #include <WINSOCK.H>
    
    class CTCPcommunicat  
    {
    public:
        CTCPcommunicat();
        virtual ~CTCPcommunicat();
    
        bool OpenConnect();
        void CloseConnect();
        int SocketRead(char* ciBuffer,long nLen);
        bool SocketSend(char* sSendMsg,int nLen);
    
    
        void SetIP(CString sIP){ m_sHostIP= sIP;};
        CString GetIP(){return m_sHostIP;};
        void    SetPort(int nPort){m_iPort = nPort;};
        int GetPort(){ return m_iPort;};
        bool SetParamnetValue(int nType,double dValue);
    
        bool    m_bConnectSuccess;
    private:
        void ReportWinsockErr(LPSTR lpszErrorMsg);
    
    
    private:
        SOCKET m_hSocket;
        unsigned short m_iPort;
        CString m_sHostIP;
        CString m_sHostName;
        SOCKADDR_IN m_sockAddr;
    
    };
    
    
    
    /****************************************************
    *              UDP协议类
    *
    *  使用UDP实现广播,因此在该网络上每台监听的设备都能收到
    *
    *  UDP协议不仅负责 开始、停止命令的发送,还需要发送开始采集和停止采集的命令(采集需要同步采集)
    *
    ******************************************************/
    
    class CUDPcommunicat
    {
    public:
        bool GetConnectFlag();
        int Receive(char* ciBuffer,long nLen);
        CUDPcommunicat();
        virtual ~CUDPcommunicat();
    
        bool Open();
        bool Close();
        
        int Broadcast(char* ciBuffer,long nLen);
        void SetPort(int nPort){m_iPort = nPort;};
        int GetPort(){return m_iPort;}; 
        void SetServerIP(CString sIP){ m_sHostIP= sIP;};
    
    private:
        SOCKET m_hSocket;
        unsigned short m_iPort;
        CString m_sHostIP;
        CString m_sHostName;
        SOCKADDR_IN m_sockAddr;
            
        bool m_bConnectFlag;//链接成功标志
    
        int  m_nType;//通讯类型  0点发送  1广播
    };
    
    
    #endif // !defined(AFX_TCPCOMMUNICAT_H__F903C55C_4E75_4F30_BFC3_D44A969C6C2D__INCLUDED_)
    
    

    TCPcommunicat.CPP

    // TCPcommunicat.cpp: implementation of the CTCPcommunicat class.
    //
    //////////////////////////////////////////////////////////////////////
    
    #include "stdafx.h"
    #include "TCPcommunicat.h"
    #include <iostream>
    
    
    #ifdef _DEBUG
    #undef THIS_FILE
    static char THIS_FILE[]=__FILE__;
    #define new DEBUG_NEW
    #endif
    
    //////////////////////////////////////////////////////////////////////
    // Construction/Destruction
    //////////////////////////////////////////////////////////////////////
    
    CTCPcommunicat::CTCPcommunicat()
    {
        m_sHostIP = "169.254.184.192";
    
    //  m_sHostIP = "169.254.209.199";
        m_iPort   = 9005;
    
        m_bConnectSuccess = false;
    }
    
    CTCPcommunicat::~CTCPcommunicat()
    {
        CloseConnect();
    }
    
    void CTCPcommunicat::ReportWinsockErr(LPSTR lpszErrorMsg)
    {
        char m_chMsgBuffer[100];
        wsprintf(m_chMsgBuffer,"\nWinsock error %d: %s\n\n", WSAGetLastError(), lpszErrorMsg);
        MessageBeep(MB_ICONSTOP);
        CString sContent(m_chMsgBuffer);
        AfxMessageBox(sContent, NULL, MB_OK | MB_ICONSTOP);
        return;
    }
    
    
    void CTCPcommunicat::CloseConnect()
    {
        try{
            closesocket(m_hSocket); // Closes the socket
            WSACleanup(); //terminates use of the Ws2_32.dll
            m_bConnectSuccess = false;
        }
        catch(CException *e)
        {
            delete e;
            throw;
        }
    }
    
    
    bool CTCPcommunicat::OpenConnect()
    {
        WSADATA wsaData;
        DWORD dwIPAddr;
    
        m_bConnectSuccess = false;
        if (WSAStartup(WINSOCK_VERSION, &wsaData))
        {
            AfxMessageBox("Could not load Windows Sockets DLL.",NULL,MB_OK);
            return false;
        }
        
        if((dwIPAddr=inet_addr(m_sHostIP))==INADDR_NONE)
        {
            AfxMessageBox("IPAddress is error!\nPlease input again!",NULL,MB_OK);
            return false;
        }
        else
        {
            m_hSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
            m_sockAddr.sin_family=AF_INET;
            m_sockAddr.sin_port=htons(m_iPort);
            m_sockAddr.sin_addr.S_un.S_addr=dwIPAddr;
            int nConnect=connect(m_hSocket,(LPSOCKADDR)&m_sockAddr,sizeof(m_sockAddr));
            
            if(nConnect)
            {
                ReportWinsockErr("Connect is error!!");
                return false;
            }
            //else
            //  AfxMessageBox("Successfully connected Server!!",NULL,MB_OK);
    
            fd_set fds;
            FD_ZERO(&fds);
            timeval tv;
            tv.tv_sec = 5;
            tv.tv_usec = 0;
    
            // wait for permission to send
            FD_SET(m_hSocket, &fds);
            int i = select(32, NULL, &fds, NULL, &tv); // write
            if (i<=0)
            {
                printf("select - error %d\n",WSAGetLastError());
                return false;
            }
        }
        m_bConnectSuccess = true;
        return true;
    }
    
    int CTCPcommunicat::SocketRead(char* ciBuffer,long nLen)
    {
        if(nLen < 0) return -1;
        
        fd_set fds;
        FD_ZERO(&fds);
        timeval tv;
        tv.tv_sec = 5;
        tv.tv_usec = 0;
        FD_SET(m_hSocket, &fds);
        int i = select(32, &fds, NULL, NULL, &tv); 
        if (i<=0)
        {
            printf("no TCP response received\n");
            return -1;
        }
    
        int nResult = recv(m_hSocket, ciBuffer, nLen, 0); // returns the number of bytes received
        return nResult;
    }
    
    bool CTCPcommunicat::SocketSend(char* sSendMsg,int nLen)
    {
        if(nLen < 1) return true;
    
        int nCharSend=send(m_hSocket,sSendMsg,nLen,0);//0,MSG_OOB
        if(nCharSend==SOCKET_ERROR)
        {
            //AfxMessageBox("Error occurred during send!!",NULL,MB_OK);
            //如果发生错误,清空缓冲区,重新链接
            return false;
        }
        return true;
    }
    
    bool CTCPcommunicat::SetParamnetValue(int nType,double dValue)
    {
        char readbuffer[100];
        readbuffer[0] = 40;
        readbuffer[1] = nType;
    
        CString sData;
        sData.Format("%.2f",dValue);
        char  *cAmp;
        cAmp = sData.GetBuffer(sData.GetLength());
        int i;
        for(i=0;i<sData.GetLength();i++)
            readbuffer[2+i] = cAmp[i];
        readbuffer[2+i] = '\n';
        
        SocketSend(readbuffer,100);
    
        return true;
    }
    
    
    
    
    //////////////////////////////////////////////////////////////////////
    // Construction/Destruction   
    // UDP链接协议 cpp
    //////////////////////////////////////////////////////////////////////
    
    CUDPcommunicat::CUDPcommunicat()
    {
    //  SOCKET m_hSocket;
    //  unsigned short m_iPort;
    //  CString m_sHostIP;
    //  CString m_sHostName;
    //  SOCKADDR_IN m_sockAddr; 
    
        m_sHostIP = "169.254.184.192";
        m_iPort   = 9009;//端口号
        m_nType = 0;//通讯类型  0点发送  1广播
        m_bConnectFlag = false;
    }
    
    CUDPcommunicat::~CUDPcommunicat()
    {
        Close();
    }
    
    bool CUDPcommunicat::Open()
    {
        WSADATA wsaData;
    //  DWORD dwIPAddr;
    
        m_bConnectFlag = false;
        if (WSAStartup(WINSOCK_VERSION, &wsaData))
        {
            AfxMessageBox("Could not load Windows Sockets DLL.",NULL,MB_OK);
            return false;
        }
        
        //m_hSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
        m_hSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);//数据报的形式
        int nBroatcast = 1;//设置为广播
        setsockopt(m_hSocket,SOL_SOCKET,SO_BROADCAST,(CHAR*)&nBroatcast,sizeof(nBroatcast) );
    
        m_sockAddr.sin_family=AF_INET;
        m_sockAddr.sin_port=htons(m_iPort);
        m_sockAddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//网段内全部发送
        
        //绑定地址
        if(bind( m_hSocket,(SOCKADDR *)&m_sockAddr,sizeof(m_sockAddr))!=0)
        {
            printf("Can't bind socket to local port!Program stop.\n");//初始化失败返回-1
            return false;
        }
                
        m_bConnectFlag = true;
        return true;
    }
    
    bool CUDPcommunicat::Close()
    {
        try{
            closesocket(m_hSocket); // Closes the socket
            WSACleanup(); //terminates use of the Ws2_32.dll
            m_bConnectFlag = false;
        }
        catch(CException *e)
        {
            delete e;
            return false;
        }
        return true;
    }
    
    
    int CUDPcommunicat::Broadcast(char* ciBuffer,long nLen)
    {
        SOCKADDR_IN  addSend;//广播发送地址
        
        addSend.sin_family = AF_INET;
        addSend.sin_addr.s_addr = htonl(INADDR_BROADCAST );
        addSend.sin_port = htons(m_iPort);//发送用的端口,可以根据需要更改
        //nSize = sizeof ( SOCKADDR_IN );}
    
        return sendto(m_hSocket,ciBuffer,nLen,0,(SOCKADDR*)&addSend,sizeof(SOCKADDR_IN) );
    }
    
    int CUDPcommunicat::Receive(char* ciBuffer,long nLen)
    {
        SOCKADDR_IN saClient;//收到的客户端地址
        int nSize = sizeof(SOCKADDR_IN);
        int nbSize = 0;
        
        if( (nbSize=recvfrom (m_hSocket,ciBuffer,nLen,0,(SOCKADDR FAR *) &saClient,&nSize))==SOCKET_ERROR )
                return -1;
    
        return nbSize;
    }
    
    //获得链接状态
    bool CUDPcommunicat::GetConnectFlag()
    {
        return m_bConnectFlag;
    }
    
    

    相关文章

      网友评论

          本文标题:CCommunicat

          本文链接:https://www.haomeiwen.com/subject/rxadvctx.html