SokcetClient c++
#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 = -;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(, ), &wsaData) != )
std::cout << "Socket版本加载失败" << std::endl;
} SokcetClient::~SokcetClient()
{
closeSocket();
} void SokcetClient::closeSocket()
{
if (m_nLocalSocket != -)
closesocket(m_nLocalSocket); //关闭socket连接 m_nLocalSocket = -;
WSACleanup(); //终止ws2_32.lib的使用
} //创建一个socket
bool SokcetClient::createSocket()
{
if (m_nLocalSocket == -)
{
/*
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 != -)
{
sockaddr_in m_nServeraddr;
memset(&m_nServeraddr, , 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 != -)
{
int rs = -;
int resultRecv = -;
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 = ;
tv.tv_usec = ;
rs = select(m_nLocalSocket, &rfds, NULL, NULL, );
if (rs > )
{
resultRecv = recv(m_nLocalSocket, m_message, size, );
if (resultRecv > )
{
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 < ) && (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 != -)
{
int size = strlen(buffer);
send(m_nLocalSocket, buffer, size, );
}
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[];
}; #endif _SOCKETCLIENT_H_
SokcetClient c++的更多相关文章
- SokcetClient VC++6.0
// SokcetClient.cpp: implementation of the SokcetClient class. // ////////////////////////////////// ...
随机推荐
- ceph报错
[ceph_deploy.mon][ERROR ] RuntimeError: config file /etc/ceph/ceph.conf exists with different conten ...
- Kafka管理与监控——查看和重设消费者组位移
kafka 0.11.0.0版本丰富了kafka-consumer-groups脚本的功能,用户可以直接使用该脚本很方便地为已有的consumer group重新设置位移. 前提必须consumer ...
- python基础知识(循环语句)
for循环.while循环.循环嵌套 for 迭代变量 In 对象: 循环体 range(start,end,step) 第一个和第三个可以省略生成一系列的连续整数 start 包括起始值 end ...
- antd <BackTop>组件的使用
<Content className={style.content} style={{ maxHeight: 'calc(100vh - 175px)',overflowY:"auto ...
- linux下配置maven并修改maven源
参考文章 <Linux下Maven的安装与使用> <aliyun阿里云Maven仓库镜像地址> <maven国内镜像配置(Ubuntu)> 下载maven,具体目录 ...
- web赛题2
@上海赛wp 微信 和 https://www.ctfwp.com/articals/2019unctf.html 后续公告https://unctf.buuoj.cn/notice.html 必看! ...
- K/3 Cloud 中FID和FMasterID的区别
经常会用到,例如物料在多组织情况下. 例如一个物料分配不同组织后,内码FID肯定是不同的,但FMaterId还是一样的,因为是用一个物料. FMASTERID是和物料编码对应的内码,即一个物料编码对应 ...
- Navicat Premium12 注册机下载及教程
1.下载Navicat Premium 官网https://www.navicat.com.cn/下载最新版本下载安装(文末,网盘地址有64位安装包和注册机下载) 2.激活Navicat Premiu ...
- VUE 1.0
现代开发模式:vue/react. 20%的时间花在了表现层 传统开发模式:jquery. 80%的时间花在了表现层 MVC——数据.表现.行为分离 视图层(表现层)<----->数据层 ...
- Oracle - 函数及多表关联
函数一般是在数据上执行的,它给数据的转换和处理提供了方便.只是将取出的数据进行处理,不会改变数据库中的值.函数根据处理的数据分为单行函数和聚合函数(组函数),组函数又被称作聚合函数,用于对多行数据进行 ...