C语言学习笔记(十五):面向接口编程

test.c

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

//初始化链接
typedef void(*init_cSockeProtocol)(void** handle);
//发送接口
typedef void(*send_cSockeProtocol)(void* handle, char* sendData, int sendlen);
//接收接口
typedef void(*recv_cSockeProtocol)(void* handle, char* recvData, int recvlen);
//关闭接口
typedef void(*close_cSockeProtocol)(void* handle);


//业务代码
void FrameWork(init_cSockeProtocol init, send_cSockeProtocol send, recv_cSockeProtocol recv, close_cSockeProtocol close)
{
	//初始化连接
	void* handle = NULL;
	init(&handle);

	//发送数据
	char sendBuf[] = "abcdefg";
	int sendlen = strlen(sendBuf);
	send(handle, sendBuf, sendlen);

	//接收数据
	char recvBuf[1024] = { 0 };
	int recvlen = 0;
	recv(handle, recvBuf, recvlen);
	printf("recvBuf=%s\n", recvBuf);
	printf("recvlen=%d\n", recvlen);

	//关闭连接
	close(handle);
	handle = NULL;

}

void test()
{
	FrameWork(init_cSocketimp, send_cSocketimp, recv_cSocketimp, close_cSocketimp);
}

int main()
{
	test();

	return 0;
}

csocketimp.c

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

struct Info
{
	char data[1024];
	int len;
};

//初始化链接
void init_cSocketimp(void** handle)
{
	if (handle == NULL)
	{
		printf("init_cSocketimp 失败\n");
		return;
	}

	struct Info* info = malloc(sizeof(struct Info));
	memset(info, 0, sizeof(struct Info));
	*handle = info;
}
//发送接口
void send_cSocketimp(void* handle, char* sendData, int sendlen)
{
	if (handle == NULL)
	{
		printf("send_cSocketimp 失败\n");
		return;
	}
	if (sendData == NULL)
	{
		printf("sendData 失败\n");
		return;
	}
	struct Info* info = (struct Info*)handle;
	strncpy(info->data, sendData, sendlen);
	info->len = sendlen;

}
//接收接口
void recv_cSocketimp(void* handle, char* recvData, int recvlen)
{
	if (handle == NULL)
	{
		printf("recv_cSocketimp 失败\n");
		return;
	}
	if (recvData == NULL)
	{
		printf("recvData 失败\n");
		return;
	}

	struct Info* info = (struct Info*)handle;
	strncpy(recvData, info->data, info->len);
	recvlen = info->len;
	 
}
//关闭接口
void close_cSocketimp(void* handle)
{
	if (handle == NULL)
	{
		return;
	}

	free(handle);
	handle = NULL;
}

csocketimp.h

#pragma once

//初始化链接
void init_cSocketimp(void** handle);
//发送接口
void send_cSocketimp(void* handle, char* sendData, int sendlen);
//接收接口
void recv_cSocketimp(void* handle, char* recvData, int recvlen);
//关闭接口
void close_cSocketimp(void* handle);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值