Socket抽象类的工程应用

本文介绍了一个简单的Socket客户端实现案例,包括接口定义、具体实现及主框架调用流程。该客户端能够进行初始化、发送与接收数据,并在完成后释放资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SocketProtocol.h

#pragma once



class SocketIF
{
public:
//客户端初始化 获取handle 上下文信息
virtual int cltSocketInit() = 0;


//客户端发报文
virtual int cltSocketSend( unsigned char *buf ,  int buflen ) = 0;


//客户端收报文
virtual int cltSocketRev( unsigned char *buf , int *buflen ) = 0;


//客户端释放资源
virtual int cltSocketDestory() = 0;


};


SocketImp1.h

#pragma once
#include "socketprotocol.h"


class SocketImp1 :public SocketIF
{
public:
SocketImp1(void);
~SocketImp1(void);


public:
int cltSocketInit();


//客户端发报文
int cltSocketSend( unsigned char *buf ,  int buflen );


//客户端收报文
int cltSocketRev( unsigned char *buf , int *buflen );


//客户端释放资源
int cltSocketDestory();
private:
char *pcommon;
int len;
};


SocketImp1.cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SocketImp1.h"




SocketImp1::SocketImp1(void)
{
}




SocketImp1::~SocketImp1(void)
{
}


int SocketImp1::cltSocketInit()
{
return 0;
}


//客户端发报文
int SocketImp1::cltSocketSend( unsigned char *buf ,  int buflen )
{
pcommon = (char *)malloc((buflen+1)*sizeof(char));
//pcommon[len-1] = 0;
len = buflen;
memcpy(pcommon,buf,buflen);
return 0;
}


//客户端收报文
int SocketImp1::cltSocketRev( unsigned char *buf , int *buflen )
{
memcpy(buf,pcommon,len);
*buflen = len;
return 0;
}


//客户端释放资源
int SocketImp1::cltSocketDestory()
{
if (pcommon != NULL)
{
delete[] pcommon;
}
return 0;
}


mainclass.cpp

#include "iostream"
#include "SocketImp1.h"
#include "SocketProtocol.h"
using namespace std;




//主框架
void mainOP01()
{
SocketIF *sIf  = new SocketImp1();


unsigned char buf[1024]; 
strcpy((char *)buf, "ddddddddddddddsssssssssssssssssssss");
int buflen = 10;


unsigned char out[1024];
int outlen = 10;
sIf->cltSocketInit();
sIf->cltSocketSend(buf, buflen);
sIf->cltSocketRev(out, &outlen);
sIf->cltSocketDestory();


}


int mainOP02(SocketIF *sIf, unsigned char *in, int inlen, unsigned char *out, int *outlen)
{
int ret = 0;
ret = sIf->cltSocketInit();
ret = sIf->cltSocketSend(in, inlen);
ret = sIf->cltSocketRev(out, outlen);
ret = sIf->cltSocketDestory();
return ret;


}


void main()
{
SocketIF *sIf  = new SocketImp1();


unsigned char buf[1024]; 
strcpy((char *)buf, "ddddddddddddddsssssssssssssssssssss");
int buflen = 10;


unsigned char out[1024];
int outlen = 10;


mainOP02(sIf, buf, buflen, out, &outlen);
cout<<out<<endl;
system("pause");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值