接口的封装与使用

接口的封装

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

typedef struct _SCK_HANDLE
{
	char version[16];
	char serverIP[16];
	int port;
	char *pBuf;
	int iBuflen;
}SCK_HANDLE;

//客户端初始化环境
__declspec(dllexport)
int cltSocket_init(void **handle)
{
	int ret = 0;
	SCK_HANDLE *sh = NULL;
	sh = (SCK_HANDLE *)malloc(sizeof(SCK_HANDLE));
	if (NULL == sh)
	{
		ret = -1;
		printf("cltSocket_init failed,ret = %d",ret);
		return ret;
	}
	strcpy(sh->version ,"1.0.0");
	strcpy(sh->serverIP, "109.123.120.209");
	sh->port = 8080;
	
	*handle = sh;
	return ret;
}

//客户端发报文
__declspec(dllexport)
int cltSocket_senddata(void *handle, unsigned char *buf, int buflen)
{
	int ret = 0;
	if (handle == NULL || buf == NULL)
	{
		ret = -1;
		return ret;
	}
	SCK_HANDLE *sh = (SCK_HANDLE*)handle;
	sh->pBuf = (char*)malloc(buflen*sizeof(char));
	if (NULL == sh->pBuf)
	{
		ret = -1;
		printf("malloc failed,buflen = %d,error = %d",buflen,ret);
	}
	memset(sh->pBuf,0x00, sizeof(buflen*sizeof(char)));
	strcpy(sh->pBuf,buf);
	sh->iBuflen = buflen;
	return ret;
}

//客户端收报文
__declspec(dllexport)
int cltSocket_resvdata(void *handle, unsigned char *buf, int *buflen)
{
	int ret = 0;
	if (handle == NULL || buf == NULL)
	{
		ret = -1;
		return ret;
	}
	SCK_HANDLE *sh = (SCK_HANDLE*)handle;
	memcpy(buf, sh->pBuf, sh->iBuflen);
	*buflen = sh->iBuflen;//获取buffer长度
	return ret;
}


//4 客户端销毁环境
_declspec(dllexport)
int cltSocket_destory(void *handle)
{
	int ret = 0;
	if (handle == NULL)
	{
		ret = -1;
		return ret;
	}
	SCK_HANDLE *sh = (SCK_HANDLE*)handle;
	if (sh->pBuf != NULL)
	{
		free(sh->pBuf);
		sh->pBuf = NULL;
	}
	free(handle);
	return ret;
}



头文件:

#ifndef _CLT_SOCKET_H__
#define _CLT_SOCKET_H__

#ifdef __cplusplus
extern "C"{
#endif
//客户端初始化环境
int cltSocket_init(void **handle);

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

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


//4 客户端销毁环境
int cltSocket_destory(void *handle);

#ifdef __cplusplus
}
#endif


#endif



接口的使用


#include <stdio.h>
#include "cltsocket.h"

int main()
{
	void *handle = NULL;

	cltSocket_init(&handle);

	cltSocket_senddata(handle,"abcdefghi",11);

	int len = 0;
	char recv[128];
	cltSocket_resvdata(handle, recv, &len);
	printf("%s\n",recv);
	cltSocket_destory(handle);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值