码迷,mamicode.com
首页 > 编程语言 > 详细

SokcetClient c++

时间:2019-10-06 20:31:07      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:har   cpi   bre   ||   use   错误   response   utf8   code   

#include "pch.h"
#include "SokcetClient.h"
#include <iostream>
#include <thread>
#include <Ws2tcpip.h>
#include "StringHelper.h"
#include "HeartBeatResponse.h"
#include "x2struct/x2struct.hpp"
#include <string.h>
#include <stdio.h>


SokcetClient::SokcetClient()
{
    m_nLocalSocket = -1;
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
        std::cout << "Socket版本加载失败" << std::endl;
}


SokcetClient::~SokcetClient()
{
    closeSocket();
}

void SokcetClient::closeSocket()
{
    if (m_nLocalSocket != -1)
        closesocket(m_nLocalSocket);    //关闭socket连接

    m_nLocalSocket = -1;
    WSACleanup();    //终止ws2_32.lib的使用
}

//创建一个socket
bool SokcetClient::createSocket()
{
    if (m_nLocalSocket == -1)
    {    
        /*
        int iMode = 1;
        WSADATA wsd;
        
        //初始化Socket环境
        if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
        {
            outputMessage("WSAStartup failed!\n");

        }
        */
        m_nLocalSocket = socket(AF_INET, SOCK_STREAM , IPPROTO_TCP);
        if (m_nLocalSocket != INVALID_SOCKET)
        {
            outputMessage(StringHelper::GBKToUTF8("客服端socket创建成功").c_str());

        }
    /*
            //调用ioctlsocket()将其设置为非阻塞模式
        int retVal = ioctlsocket(m_nLocalSocket, FIONBIO, (u_long FAR*)&iMode);
        if (retVal == SOCKET_ERROR)
        {
            outputMessage("ioctlsocket failed!");
            WSACleanup();
        }*/
    
        
    }


    return false;
}

bool SokcetClient::Myconnect(const char* ip, const unsigned short prot)
{
    int nRet = SOCKET_ERROR;
    if (m_nLocalSocket != -1)
    {
        sockaddr_in m_nServeraddr;
        memset(&m_nServeraddr, 0, sizeof(m_nServeraddr));
        m_nServeraddr.sin_family = AF_INET;
        m_nServeraddr.sin_port = htons(prot);
        m_nServeraddr.sin_addr.s_addr = inet_addr(ip);
        
        nRet = connect(m_nLocalSocket, (sockaddr*)&m_nServeraddr, sizeof(m_nServeraddr));//成功返回0。否则返回SOCKET_ERROR

        if (nRet == SOCKET_ERROR)
        {
            outputMessage("服务器连接失败!");
            return false;
        }

        outputMessage("服务器连接成功!");
        //std::string data ="{\"bizCode\":\"B1001\",\"parkingNo\":\"1000000184\",\"clientNo\":\"1\",\"reqNo\":\"201909291613278736\",\"clientName\":\"大门岗亭\",\"sign\":\"57DCE7C04A3EF22BF2305281A98A57B2\"}\n\0";
        //std::string strTemp = StringHelper::GBKToUTF8(data);
        //outputMessage(data.c_str());
        //Mysend(strTemp.c_str());
        //Myrecv();

        return true;
    }

    return false;
}



void SokcetClient::Myrecv()
{


    if (m_nLocalSocket != -1)
    {
        int rs = -1;
        int resultRecv = -1;
        fd_set rfds;
        while (true)
        {
        
            int size = sizeof(m_message);
            memset(m_message, \0, size);
            FD_ZERO(&rfds);
            FD_SET(m_nLocalSocket, &rfds);
            struct timeval tv;
            tv.tv_sec = 2;
            tv.tv_usec = 0;
            rs = select(m_nLocalSocket, &rfds, NULL, NULL, 0);
            if (rs > 0) 
            {
                resultRecv = recv(m_nLocalSocket, m_message, size, 0);
                if (resultRecv > 0)
                {
                    HeartBeatResponse heartBeatResponse;
                    x2struct::X::loadjson(m_message, heartBeatResponse, false);
                    string json = x2struct::X::tojson(heartBeatResponse);


                    //输出消息
                    outputMessage(json.c_str());

                    memset(m_message, \0, size);

                }
                else
                {
                    //这几种错误码,认为连接是正常的,继续接收
                    if ((resultRecv < 0) && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
                    {
                        continue;//继续接收数据
                    }
                    //outputMessage("与服务器连接中断!");
                    //break;//跳出接收循环
                }
            }
        }
        /*
#define MAXBUF 1024
        int  len;
    
        char buffer[MAXBUF];
    
        char heartbeat[2048] = "{\"bizCode\":\"B1001\",\"parkingNo\":\"1000000184\",\"clientNo\":\"1\",\"reqNo\":\"201909291613278736\",\"clientName\":\"大门岗亭\",\"sign\":\"57DCE7C04A3EF22BF2305281A98A57B2\"}\n";
        fd_set rfds;
        struct timeval tv;
        int retval, maxfd = -1;
        while (1)
        {
            FD_ZERO(&rfds);
            FD_SET(0, &rfds);
            maxfd = 0;

            FD_SET(m_nLocalSocket, &rfds);
            if (m_nLocalSocket > maxfd)
                maxfd = m_nLocalSocket;

            tv.tv_sec = 2;
            tv.tv_usec = 0;

            retval = select(maxfd + 1, &rfds, NULL, NULL, &tv);
            if (retval == -1)
            {
                printf("Will exit and the select is error! %s", strerror(errno));
                break;
            }
            else if (retval == 0)
            {
                //printf("No message comes, no buttons, continue to wait ...\n");
                len = send(m_nLocalSocket, heartbeat, strlen(heartbeat), 0);
                if (len < 0)
                {
                    printf("Message ‘%s‘ failed to send !               The error code is %d, error message ‘%s‘\n",
                        heartbeat, errno, strerror(errno));
                    break;
                }
                else
                {
                    printf("News: %s \t send, sent a total of %d bytes!\n",
                        heartbeat, len);
                }

                continue;
            }
            else
            {
                if (FD_ISSET(m_nLocalSocket, &rfds))
                {
                    memset(buffer, 0,MAXBUF + 1);
                    len = recv(m_nLocalSocket, buffer, MAXBUF, 0);


                    if (len > 0)
                    {
                        printf("Successfully received the message: ‘%s‘,%d bytes of data\n",
                            buffer, len);
                    }
                    else
                    {
                        if (len < 0)
                            printf("Failed to receive the message!                     The error code is %d, error message is ‘%s‘\n",
                                errno, strerror(errno));
                        else
                            printf("Chat to terminate!\n");


                        break;
                    }
                }


                if (FD_ISSET(0, &rfds))
                {
                    memset(buffer,0, MAXBUF + 1);
                    fgets(buffer, MAXBUF, stdin);


                    if (!strncmp(buffer, "quit", 4))
                    {
                        printf("Own request to terminate the chat!\n");
                        break;
                    }


                    len = send(m_nLocalSocket, buffer, strlen(buffer) - 1, 0);
                    if (len < 0)
                    {
                        printf("Message ‘%s‘ failed to send !                 The error code is %d, error message ‘%s‘\n",
                            buffer, errno, strerror(errno));
                        break;
                    }
                    else
                    {
                        printf("News: %s \t send, sent a total of %d bytes!\n",
                            buffer, len);
                    }
                }
            }
        }*/
    }
    else
    {
        outputMessage("当前与服务器未连接!");
    }
}

void SokcetClient::Mysend(const char* buffer)
{
    if (m_nLocalSocket != -1)
    {
        int size = strlen(buffer);
        send(m_nLocalSocket, buffer, size, 0);
    }
    else
    {
        outputMessage("当前与服务器未连接");
    }
}

void SokcetClient::outputMessage(const char * outstr)
{
    std::cout << outstr << std::endl;
}

 

 

#pragma once

#ifndef _SOCKETCLIENT_H_
#define _SOCKETCLIENT_H_

#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")  //加载 ws2_32.dll


class SokcetClient
{
public:
    SokcetClient();
    ~SokcetClient();

    bool createSocket();
    void closeSocket();

    bool Myconnect(const char* ip, const unsigned short prot);
    void Mysend(const char* buffer);
    void Myrecv();

    void outputMessage(const char* outstr);

private:
    SOCKET m_nLocalSocket;
    char m_message[1024];
};


#endif _SOCKETCLIENT_H_

 

SokcetClient c++

标签:har   cpi   bre   ||   use   错误   response   utf8   code   

原文地址:https://www.cnblogs.com/zclaude/p/11628279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!