transferServiceExe/NetSocket.cpp

597 lines
13 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "NetSocket.h"
#include "json/json.h"
#pragma comment(lib, "ws2_32.lib")
CNetSocket::CNetSocket()
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR)
printf("WSAStartup() Error");
//cout << "Error at WSAStartup()" << endl;
}
CNetSocket::~CNetSocket()
{
WSACleanup();
}
int CNetSocket::PostForm(char * RemoteHostIP, int RemoteHostPort, char * lpURL, string formData, CFaceAuthResult &ret)
{
//log.WriteStrToFile("开始网络");
int SocketId, Result, optval = 1;
struct sockaddr_in sServerAddr;
string strBody;
ret.code = -1;
sServerAddr.sin_family = AF_INET;
sServerAddr.sin_addr.s_addr = inet_addr(RemoteHostIP);
//sServerAddr->sin_addr.s_addr = INADDR_ANY;
sServerAddr.sin_port = htons(RemoteHostPort);
if ((SocketId = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
return -1;
}
int timeout = 10000; // 超时时间为10秒单位是毫秒
// 设置发送超时
if (setsockopt(SocketId, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
// 错误处理
strBody = "set send time out failed\n";
//log.WriteStrToFile(strBody);
printf("%s\n",strBody.c_str());
shutdown(SocketId, 2);
::closesocket(SocketId);
return -1;
}
// 设置接收超时
if (setsockopt(SocketId, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
// 错误处理
strBody = "set receive time out failed\n";
//log.WriteStrToFile(strBody);
printf("%s\n", strBody.c_str());
shutdown(SocketId, 2);
::closesocket(SocketId);
return -1;
}
optval = 1;
setsockopt(SocketId, SOL_SOCKET, SO_KEEPALIVE,
(char *)&optval, sizeof(int));
strBody = "connect network";
//log.WriteStrToFile(strBody);
Result = connect(SocketId, (struct sockaddr*)&sServerAddr, sizeof(struct sockaddr_in));
if (Result != 0)
{
strBody = "connect failed";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
shutdown(SocketId, 2);
::closesocket(SocketId);
return -1;
}
strBody = "connect success";
//log.WriteStrToFile(strBody);
//
// Format the HTTP request
//
// request buffer
char *szGetBuffer = new char[MAX_CMD_SIZE * MAX_CMD_SIZE];
sprintf_s(szGetBuffer, MAX_CMD_SIZE * MAX_CMD_SIZE, "POST %s?file=%s HTTP/1.0\r\nHost:%s:%d\r\nContent-Type:application/x-www-form-urlencoded;charset=UTF-8;\r\n\r\n",
lpURL, formData.c_str(), RemoteHostIP, RemoteHostPort);
strBody = "request api";
//log.WriteStrToFile(strBody);
//发送Post请求
Result = send(SocketId, szGetBuffer, strlen(szGetBuffer), 0);
if (Result == -1)
{
strBody = "request api failed";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
shutdown(SocketId, 2);
::closesocket(SocketId);
delete[]szGetBuffer;
return -1;
}
strBody = "request api success";
//log.WriteStrToFile(strBody);
//userlog("function send success, the send string is \n %s \n return Value is %d",szGetBuffer,Result);
/*
* 接受Post请求的返回结果
*/
// recv http header
string header;
int headerLength = RecvHttpHeader(SocketId, header);
strBody = "";
if (headerLength > 0)
{
int contentLength = FindContentLength(header);
RecvHttpBody(SocketId, strBody, contentLength);
}
else
{
//userlog("the return string is not http protptype");
}
printf("%s\n", strBody.c_str());
::closesocket(SocketId);
delete[]szGetBuffer;
ret.code = 0;
return 0;
}
int CNetSocket::FindContentLength(string header)
{
std::transform(header.begin(), header.end(), header.begin(), (int(*)(int)) tolower);
string::size_type pos = header.find("content-length", 0);
if (pos != string::npos)
{
string::size_type posEnd = header.find("\r\n", pos);
string contentString = header.substr(pos, posEnd - pos);
//userlog(contentString.c_str());
pos = contentString.find(":", 0);
string strLength = contentString.substr(pos + 1);
return (int)std::strtol(strLength.c_str(), NULL, 10);
}
return 0;
}
int CNetSocket::recvPacketSize(SOCKET s)
{
char header[8] = { 0 };
int len = 0;
//确保收到8个字节
len = recv(s, header, 8, 0);
if (SOCKET_ERROR == len)
{
return -1;
}
if ('V' == header[0] && 'Z' == header[1])
{
int toRecvLen = 0;
memcpy(&toRecvLen, &header[4], 4);
return header[2] == 1 ? 0 : htonl(toRecvLen);
}
return -1;
}
int CNetSocket::RecvData(SOCKET s, string& data)
{
int nRet = 0;
int toRecvLen = recvPacketSize(s);
char *pBuf = NULL;
char buf[1] = { 0 };
int nRecv = 0;
int nCurRecv = 0;
int i = 0;
if (toRecvLen > 0)
{
pBuf = new char[toRecvLen + 1];
ZeroMemory(pBuf, toRecvLen + 1);
nCurRecv = recv(s, pBuf, toRecvLen, 0);
nRecv += nCurRecv;
data.append(pBuf, nCurRecv);
//printf("toRecvLen=%d,nRecv=%d\r\n", toRecvLen, nRecv);
while (nRecv < toRecvLen) {
ZeroMemory(pBuf, toRecvLen + 1);
nCurRecv = recv(s, pBuf, toRecvLen, 0);
nRecv += nCurRecv;
data.append(pBuf, nCurRecv);
}
delete[]pBuf;
}
else
{
//socket error
nRet = -1;
}
return nRet;
}
size_t CNetSocket::RecvHttpHeader(int socket, string& header)
{
header.clear();
char chRecvBuf[1];
char endBytes[] = { 13, 10, 13, 10 };
int posCompare = 0;
while (true)
{
int b = recv(socket, chRecvBuf, 1, 0);
if (b <= 0)
break;
header.append(chRecvBuf, 1);
if (endBytes[posCompare] == chRecvBuf[0])
{
posCompare++;
if (posCompare == sizeof(endBytes))
{
break;
}
}
else
{
posCompare = 0;
}
}
return header.length();
}
int CNetSocket::RecvHttpHeaderLength(int socket, string& length)
{
length.clear();
char chRecvBuf[1];
char endBytes[] = { 13, 10 };
int posCompare = 0;
while (true)
{
int b = recv(socket, chRecvBuf, 1, 0);
if (b <= 0)
break;
length.append(chRecvBuf, 1);
if (endBytes[posCompare] == chRecvBuf[0])
{
posCompare++;
if (posCompare == sizeof(endBytes))
{
break;
}
}
else
{
posCompare = 0;
}
}
return length.length();
}
int CNetSocket::RecvHttpBody(int socket, string& body, int contentLen)
{
body.clear();
char *chRecvBuf = new char[contentLen + 1];
ZeroMemory(chRecvBuf, contentLen + 1);
int b = recv(socket, chRecvBuf, contentLen + 1, 0);
body.append(chRecvBuf, contentLen);
delete[]chRecvBuf;
return body.length();
}
int CNetSocket::PostJson(char * RemoteHostIP, int RemoteHostPort, char * lpURL, string jsonData, string &strBody)
{
int SocketId, Result, optval = 1;
struct sockaddr_in sServerAddr;
setlocale(LC_ALL, "Chinese-simplified");
strBody = "initialize";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
sServerAddr.sin_family = AF_INET;
sServerAddr.sin_addr.s_addr = inet_addr(RemoteHostIP);
//sServerAddr->sin_addr.s_addr = INADDR_ANY;
sServerAddr.sin_port = htons(RemoteHostPort);
if ((SocketId = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
return -1;
}
//设置KeepAlive
optval = 1;
setsockopt(SocketId, SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(int));
//设置发送超时时间为5秒
int sendTimeout = 10000;
if (setsockopt(SocketId, SOL_SOCKET, SO_SNDTIMEO, (char *)&sendTimeout, sizeof(int)) < 0) {
// 错误处理,例如打印错误信息
perror("setsockopt SO_SNDTIMEO");
}
//设置接收超时时间为5秒
int recvTimeout = 10000;
if (setsockopt(SocketId, SOL_SOCKET, SO_RCVTIMEO, (char *)&recvTimeout, sizeof(int)) < 0) {
// 错误处理,例如打印错误信息
perror("setsockopt SO_SNDTIMEO");
}
strBody = "connect";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
Result = connect(SocketId, (struct sockaddr*)&sServerAddr, sizeof(struct sockaddr_in));
DWORD err = GetLastError();
if (Result != 0)
{
strBody = "connect error";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
::closesocket(SocketId);
return -1;
}
strBody = "connect success";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
char *szGetBuffer = new char[1024 * 1024];
ZeroMemory(szGetBuffer, 1024 * 1024);
//jsonData = "{\"name\": \"1\"}";
sprintf_s(szGetBuffer, 1024 * 1024, "POST %s HTTP/1.1\r\nHost:%s:%d\r\nContent-Type:application/json\r\nContent-Length:%d\r\n\r\n%s",
lpURL, RemoteHostIP, RemoteHostPort, jsonData.length(), jsonData.c_str());
//printf("%s\n", szGetBuffer);
//WriteStrToFile(szGetBuffer);
strBody = "request interface";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
//发送Post请求
Result = send(SocketId, szGetBuffer, strlen(szGetBuffer), 0);
if (Result == -1)
{
strBody = "request interface error";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
::closesocket(SocketId);
delete[]szGetBuffer;
return -1;
}
strBody = "request interface success";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
//userlog("function send success, the send string is \n %s \n return Value is %d",szGetBuffer,Result);
/*
* 接受Post请求的返回结果
*/
// recv http header
string header;
int headerLength = RecvHttpHeader(SocketId, header);
string length;
//int tempLength = RecvHttpHeaderLength(SocketId, length);
strBody = "";
if (headerLength > 0)
{
int contentLength = FindContentLength(header);
RecvHttpBody(SocketId, strBody, contentLength);
}
else
{
//userlog("the return string is not http protptype");
}
::closesocket(SocketId);
delete[]szGetBuffer;
return 0;
}
int CNetSocket::sendCmd(char * RemoteHostIP, int RemoteHostPort, char cmd[], string &data)
{
SOCKET SocketId;
int Result, optval = 1;
struct sockaddr_in sServerAddr;
string strBody;
//printf("cmd is %s\n", cmd);
//strBody = "初始化";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
sServerAddr.sin_family = AF_INET;
sServerAddr.sin_addr.s_addr = inet_addr(RemoteHostIP);
//sServerAddr->sin_addr.s_addr = INADDR_ANY;
sServerAddr.sin_port = htons(RemoteHostPort);
if ((SocketId = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
strBody = "init socket failed";
printf("%s\n", strBody.c_str());
return -1;
}
optval = 1;
setsockopt(SocketId, SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(int));
//strBody = "连接网络";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
Result = connect(SocketId, (struct sockaddr*)&sServerAddr, sizeof(struct sockaddr_in));
DWORD err = GetLastError();
if (Result != 0)
{
strBody = "connect failed";
printf("%s\n",strBody.c_str());
//log.WriteStrToFile(strBody);
::closesocket(SocketId);
return -1;
}
strBody = "connect success";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
int len = strlen(cmd) + 1;
char buff[8] = { 0 };
buff[0] = 'V';
buff[1] = 'Z';
int nlen = htonl(len);
memcpy(&buff[4], &nlen, 4);
Result = send(SocketId, buff, 8, 0);
if (Result == 8)
{
Result = send(SocketId, cmd, len, 0);
if (Result == -1)
{
strBody = "request host failed";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
::closesocket(SocketId);
return -1;
}
RecvData(SocketId, data);
//printf("recv:");
//printf("%s\n", data.c_str());
}
else
{
::closesocket(SocketId);
return -1;
}
::closesocket(SocketId);
return 0;
}
int CNetSocket::sendCmds(char * RemoteHostIP, int RemoteHostPort, char cmdInit[],char cmdGetStatus[], string &data)
{
SOCKET SocketId;
int Result, optval = 1;
struct sockaddr_in sServerAddr;
string strBody;
//strBody = "初始化";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
sServerAddr.sin_family = AF_INET;
sServerAddr.sin_addr.s_addr = inet_addr(RemoteHostIP);
//sServerAddr->sin_addr.s_addr = INADDR_ANY;
sServerAddr.sin_port = htons(RemoteHostPort);
if ((SocketId = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
printf("%s\n", strBody.c_str());
return -1;
}
optval = 1;
setsockopt(SocketId, SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(int));
//strBody = "连接网络";
//printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
Result = connect(SocketId, (struct sockaddr*)&sServerAddr, sizeof(struct sockaddr_in));
DWORD err = GetLastError();
if (Result != 0)
{
strBody = "连接失败";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
::closesocket(SocketId);
return -1;
}
strBody = "连接成功";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
int nlen;
int len;
char buff[8] = { 0 };
len = strlen(cmdInit) + 1;
buff[0] = 'V';
buff[1] = 'Z';
nlen = htonl(len);
memcpy(&buff[4], &nlen, 4);
Result = send(SocketId, buff, 8, 0);
if (Result == 8)
{
Result = send(SocketId, cmdInit, len, 0);
if (Result == -1)
{
strBody = "请求接口失败";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
::closesocket(SocketId);
return -1;
}
RecvData(SocketId, data);
printf("recv:");
printf("%s\n", data.c_str());
}
else
{
::closesocket(SocketId);
return -1;
}
data = "";
len = strlen(cmdGetStatus) + 1;
buff[0] = 'V';
buff[1] = 'Z';
nlen = htonl(len);
memcpy(&buff[4], &nlen, 4);
Result = send(SocketId, buff, 8, 0);
if (Result == 8)
{
Result = send(SocketId, cmdGetStatus, len, 0);
if (Result == -1)
{
strBody = "请求接口失败";
printf("%s\n", strBody.c_str());
//log.WriteStrToFile(strBody);
::closesocket(SocketId);
return -1;
}
}
RecvData(SocketId, data);
printf("recv:");
printf("%s\n", data.c_str());
data = "";
RecvData(SocketId, data);
printf("recv:");
printf("%s\n", data.c_str());
::closesocket(SocketId);
return 0;
}