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. // ////////////////////////////////// ...
随机推荐
- error: atomic: 没有那个文件或目录
Linux下编译的时候遇到一个问题,就是提示 error: atomic: 没有那个文件或目录 执行的命令是gcc -o myCXXLog myCXXLog.c 经过网上搜索,解决方法有二 (1 ...
- 一百二十四:CMS系统之首页导航条和代码抽离
模板抽离 由于前后台的模板有些需要的元素如,js,css是相同的,这里抽离出来做base模板 {% from "common/_macros.html" import static ...
- 在SuSE安装wifidog认证服务器和网关
在SuSE安装认证服务器和网关 在openSuSE 10.3安装wifidog 认证服务器和网关在同台设备中安装完毕.以下是openSuSE的详细安装指南.这个安装是非常初级的,所以请验证或更正. - ...
- Scala中的列表可以添加元素吗?
列表或许是Scala程序中最常用到的数据结构了,其与数组非常相似,最重要的两点差别为: 1.列表是不可变的: 2.列表具有递归结构,而数组是连续的. 在实际使用中非常容易这样用: val a = Li ...
- mySQL的简单安装和配置
MySQL的安装和配置 1.去官网下载mysql-5.6.29-winx64.zip包.地址: http://dev.mysql.com/downloads/mysql/5.6.html 2,把安装包 ...
- 日志备份shell脚本
脚本注释已经很清楚了,就不再啰嗦了. 算了,还是多说一句吧,脚本设计完成之后,就可以加入计划任务,让电脑帮你打工了. 注:关于计划任务crontab,我会专门写一篇笔记. 最最最后一句, find $ ...
- itchat相关资料
https://itchat.readthedocs.io/zh/latest/ https://www.v2ex.com/t/306804 http://blog.csdn.net/th_num/a ...
- dfs入门-cogs1640[黑白图像]
题目链接:http://cogs.pro:8081/cogs/problem/problem.php?pid=vxSmxkeqa [题目描述] 输入一个n×n的黑白图像(1表示黑色,0表示白色),任务 ...
- java 8 Base64用法
Java 8的java.util套件中,新增了Base64的类别,可以用来处理Base64的编码与解码,用法如下: final Base64.Decoder decoder = Base64.getD ...
- 【Python】【demo实验13】【练习实例】【暂停1s输出】
原题: 暂停1s输出 使用time 模块: >>> dir(time) ['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__ ...