VC6简单封装TCP客户端
本帖最后由 lichunfeng 于 2020-4-8 00:03 编辑由于写补丁经常使用VC6,偶尔会用到访问服务器返回一些东西,便自己封装了一个简单的TCP客户端,具体见代码。
代码应该存在BUG,以及不足,希望大家可以指正出来。
~~~~~~~~~~~~
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")//加载 ws2_32.dll
class ClintTcp
{
public:
ClintTcp();//构造函数
~ClintTcp();//析构函数
BOOL MyConnet(const char* ip,int port);//连接
BOOL Close();//断开
BOOL MySend(const char* buff,int len);//发送
BOOL SendAndRecv(char* sbuff,int len,char* rbuff);//发送并取回
BOOL MyRecv(char* buff);//接收
BOOL IsConnect();//是否连接中
int GetLocalPort();//取本机端口
protected:
private:
SOCKET m_LocalSocket;//句柄
};
//cpp文件
include "StdAfx.h"
#include "TcpCilent.h"
ClintTcp::ClintTcp(){
m_LocalSocket = -1;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
printf("创建版本失败");
}
ClintTcp::~ClintTcp(){
closesocket(m_LocalSocket);
}
BOOL ClintTcp::MyConnet(const char* ip,int port){//连接服务器
if (m_LocalSocket > 0)
{closesocket(m_LocalSocket);}
m_LocalSocket = socket (PF_INET,SOCK_STREAM,IPPROTO_TCP);
if (m_LocalSocket == -1)
{
return FALSE;
}
sockaddr_in m_Serveraddr;
memset(&m_Serveraddr,0,sizeof(m_Serveraddr));
m_Serveraddr.sin_family = AF_INET;
m_Serveraddr.sin_port = htons(port);
m_Serveraddr.sin_addr.s_addr = inet_addr(ip);
int conret = connect(m_LocalSocket,(sockaddr*)&m_Serveraddr,sizeof(m_Serveraddr));
if (conret == SOCKET_ERROR)
{
printf("连接服务器失败! \n");
closesocket(m_LocalSocket);
m_LocalSocket = -1;
return FALSE;
}
printf("连接服务器成功! \n");
return TRUE;
}
BOOL ClintTcp::Close(){
if (m_LocalSocket > 0)
{
closesocket(m_LocalSocket);
return TRUE;
}
return FALSE;
}
BOOL ClintTcp::MySend(const char* buff,int len){
int len_al = send(m_LocalSocket,buff,len,0);
printf("实际发送了 %d 字节 \n",len_al);
return TRUE;
}
BOOL ClintTcp::MyRecv(char* buff){
memset(buff,0,1000);//清空缓冲区
int len = recv(m_LocalSocket,buff,1000,0);
if (len<=0)
{
return FALSE;
}
return TRUE;
}
BOOL ClintTcp::SendAndRecv(char* sbuff,int slen,char* rbuff){
MySend(sbuff,slen);
BOOL bRecv;
while (true)
{
bRecv = MyRecv(rbuff);
if (bRecv)
{
break;
}
}
return true;
}
int main(int argc, char* argv[])
{
//测试
ClintTcp* nClintTcp = new ClintTcp();
nClintTcp->MyConnet("127.0.1.1",9001);//连接服务端 IP,端口
char maccode = "111111111111111111"
char m_buff;
nClintTcp->SendAndRecv(maccode,sizeof(maccode),m_buff);
printf("接收:%s \n",m_buff);
return 0;
}
~~~~~~~
感谢楼主分享,学习学习了 牛逼了,牛逼了。 学习一下socket 这个... tcp就存着: 超时,重连,重发, 去重复的问题。你这也太简单了把。
哦, 忘了,还有粘包的处理。 谢谢楼主,收藏了 有大佬出过完更加完善的版本吗?想要啊 感谢分享,先收藏着
页:
[1]