接口的封装
#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;
}