面向接口编程
#include<iostream> #include<stdlib.h> #include<stdio.h> #include<string.h> using namespace std; ////初始化 typedef void(*init_CSocketProtocol)(void** handle); //发送接口 typedef void(*send_CSocketProtocol)(void* handle, char* sendData, int sendLen); //接收接口 typedef void(*recv_CSocketProtocol)(void* handle, char* recvData, int* recvLen); //关闭 typedef void(*close_CSocketProtocol)(void* handle); struct Info { char data[1024]; int len; }; //初始化 void init_CSockImpl(void** handle) { struct Info* info = (struct Info*)malloc(sizeof(struct Info)); memset(info, 0, sizeof(Info)); *handle = info; } //发送接口 void send_CSockImpl(void* handle, char* sendData, int sendLen) { if (NULL == handle)return; if (NULL == sendData)return; struct Info* info = (struct Info*)handle; strncpy_s(info->data, sendData, sendLen); info->len = sendLen; cout << "发送数据:" << sendData << endl; } //接收接口 void recv_CSockImpl(void* handle, char* recvData, int* recvLen) { if (NULL == handle)return; if (NULL == recvData)return; if (NULL == recvLen)return; struct Info* info = (struct Info*)handle; char s[1024]; strncpy_s(recvData,1024, info->data,sizeof(info->data)); //strncpy_s(s, info->data, info->len); //recvData = s; *recvLen = info->len; cout << "接收数据:" << recvData << endl; } //关闭 void close_CSockImpl(void* handle) { if (NULL == handle)return; free(handle); handle = NULL; } //业务 void FramWork(init_CSocketProtocol init, send_CSocketProtocol send, recv_CSocketProtocol recv, close_CSocketProtocol close) { //初始化链接 void *handle = nullptr; init(&handle); //发送数据 char buf[1024] = "hello world"; int len = strlen(buf); send(handle, buf, len); //接受数据 char recvBuf[1024] = { 0 }; int recvlen = 0; recv(handle, recvBuf, &recvlen); //关闭链接 close(handle); } void test() { FramWork(init_CSockImpl, send_CSockImpl, recv_CSockImpl, close_CSockImpl); } int main() { test(); system("pause"); }