2026打造你的嵌入式职场核心竞争力
大家好,我是杂烩君。
在嵌入式开发中,TCP网络通信是我们经常要面对的需求。不管是做物联网设备、工业控制系统,还是各种网络应用,都离不开TCP的身影。
但每次写TCP通信代码的时候,你是不是也有这样的感觉:socket、bind、listen、accept这一套流程写下来,参数一堆,结构体嵌套,代码重复度高,每次都要查资料确认参数怎么填?
今天就和大家一起封装一套实用的TCP应用接口。
1. 为什么要封装TCP接口
先来看看标准的TCP通信流程。对于服务端来说,需要经历创建socket → 绑定地址 → 监听 → 接受连接这几个步骤;客户端则需要创建socket → 连接服务器。这个过程用流程图表示如下:
这个流程本身不复杂,但是每个函数的参数设置都比较繁琐。比如bind函数,需要填充sockaddr_in结构体,设置地址族、IP地址、端口号,还要注意字节序转换。如果每次都手写这些代码,不仅效率低,而且容易出错。
所以,我们的封装目标很明确:把复杂的参数设置和重复性的代码隐藏起来,对外提供简洁易用的接口。
2. 封装方案设计
我们的封装思路是这样的:将TCP通信中的常用操作抽象成几个核心函数,每个函数只需要传入最关键的参数,内部自动完成所有细节处理。整个封装的架构如下:
主要封装了以下几个函数:
tcp_init:服务端初始化,一个函数搞定socket创建、bind、listen全流程
tcp_accept:接受客户端连接,简化参数传递
tcp_connect:客户端连接服务器,只需IP和端口
tcp_send:发送数据
tcp_blocking_recv:阻塞方式接收数据
tcp_nonblocking_recv:非阻塞方式接收数据,带超时控制
tcp_close:关闭连接
3. 核心代码实现
下面我们来看看具体的实现。先从头文件开始:
tcp_socket.h:
#ifndef TCP_SOCKET_H
#define TCP_SOCKET_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <stdint.h>
#define MAX_CONNECT_NUM 10 /* 最大连接队列长度 */
#define TCP_NO_TIMEOUT 0 /* 无超时 */
/*===========================================================================
* 错误码定义
*=========================================================================*/
#define TCP_SUCCESS 0 /* 成功 */
#define TCP_ERR_SOCKET -1 /* socket创建失败 */
#define TCP_ERR_SETSOCKOPT -2 /* setsockopt设置失败 */
#define TCP_ERR_BIND -3 /* bind绑定失败 */
#define TCP_ERR_LISTEN -4 /* listen监听失败 */
#define TCP_ERR_ACCEPT -5 /* accept接受连接失败 */
#define TCP_ERR_CONNECT -6 /* connect连接失败 */
#define TCP_ERR_TIMEOUT -7 /* 连接超时 */
#define TCP_ERR_SEND -8 /* 发送失败 */
#define TCP_ERR_RECV -9 /* 接收失败 */
/*===========================================================================
* API 接口
*=========================================================================*/
int tcp_init(const char* ip, int port);
int tcp_accept(int server_fd, char *client_ip, int ip_len, int *client_port);
int tcp_connect(const char* ip, int port, int timeout_sec);
int tcp_nonblocking_recv(int conn_sockfd, void *rx_buf, int buf_len,
int timeval_sec, int timeval_usec);
int tcp_blocking_recv(int conn_sockfd, void *rx_buf, uint16_t buf_len);
int tcp_send(int conn_sockfd, uint8_t *tx_buf, uint16_t buf_len);
int tcp_send_all(int conn_sockfd, uint8_t *tx_buf, uint16_t buf_len);
void tcp_close(int sockfd);
#endif
头文件中定义了7个核心函数接口:
错误码系统:明确的错误码定义,方便调试和错误处理
参数精简:只保留必需参数,减少使用复杂度
功能完整:涵盖TCP通信的所有核心场景
3.1 实现细节
tcp_socket.c:
下面我们重点看几个关键函数的实现。
3.1.1 tcp_init - 服务端初始化
int tcp_init(const char* ip, int port)
{
int optval = 1;
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0)
{
perror("socket");
return TCP_ERR_SOCKET;
}
/* 解除端口占用 */
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0)
{
perror("setsockopt");
close(server_fd);
return TCP_ERR_SETSOCKOPT;
}
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(struct sockaddr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
if (NULL == ip)
{
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
}
else
{
server_addr.sin_addr.s_addr = inet_addr(ip);
}
if (bind(server_fd, (struct sockaddr*)&server_addr,sizeof(struct sockaddr)) < 0)
{
perror("bind");
close(server_fd);
return TCP_ERR_BIND;
}
if(listen(server_fd, MAX_CONNECT_NUM) < 0)
{
perror("listen");
close(server_fd);
return TCP_ERR_LISTEN;
}
return server_fd;
}
这个函数把socket创建、设置端口复用、地址绑定、开始监听这四个步骤合并到一起。调用时只需传入IP地址和端口号,如果IP传NULL则自动绑定所有网卡地址(INADDR_ANY)。使用SO_REUSEADDR选项避免程序重启时的"Address already in use"错误。
3.1.2 tcp_accept - 接受客户端连接
int tcp_accept(int server_fd, char *client_ip, int ip_len, int *client_port)
{
struct sockaddr_in client_addr = {0};
socklen_t addrlen = sizeof(struct sockaddr);
int new_fd = accept(server_fd, (struct sockaddr*) &client_addr, &addrlen);
if(new_fd < 0)
{
perror("accept");
return TCP_ERR_ACCEPT;
}
/* 返回客户端IP和端口信息 */
if (client_ip != NULL && ip_len > 0)
{
snprintf(client_ip, ip_len, "%s", inet_ntoa(client_addr.sin_addr));
}
if (client_port != NULL)
{
*client_port = ntohs(client_addr.sin_port);
}
return new_fd;
}
这个函数封装了accept调用,并增强了功能:可以获取客户端的IP和端口信息。如果不需要这些信息,传NULL即可。注意addrlen参数类型是socklen_t,符合POSIX标准。
使用示例:
/* 需要客户端信息 */
char client_ip[32];
int client_port;
int client_fd = tcp_accept(server_fd, client_ip, sizeof(client_ip), &client_port);
printf("客户端: %s:%dn", client_ip, client_port);
/* 不需要客户端信息 */
int client_fd = tcp_accept(server_fd, NULL, 0, NULL);
3.1.3 tcp_connect - 客户端连接(支持超时)
int tcp_connect(const char *ip, int port, int timeout_sec)
{
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0)
{
perror("socket");
return TCP_ERR_SOCKET;
}
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(struct sockaddr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = inet_addr(ip);
/* 无超时,使用系统默认(阻塞模式) */
if (timeout_sec == 0)
{
if (connect(server_fd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr)) < 0)
{
perror("connect");
close(server_fd);
return TCP_ERR_CONNECT;
}
return server_fd;
}
/* 有超时,使用非阻塞模式 */
int flags = fcntl(server_fd, F_GETFL, 0);
if (flags < 0 || fcntl(server_fd, F_SETFL, flags | O_NONBLOCK) < 0)
{
perror("fcntl");
close(server_fd);
return TCP_ERR_SOCKET;
}
int ret = connect(server_fd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr));
if (ret < 0)
{
if (errno != EINPROGRESS)
{
perror("connect");
close(server_fd);
return TCP_ERR_CONNECT;
}
/* 使用select等待连接完成 */
fd_set writeset;
struct timeval timeout;
timeout.tv_sec = timeout_sec;
timeout.tv_usec = 0;
FD_ZERO(&writeset);
FD_SET(server_fd, &writeset);
ret = select(server_fd + 1, NULL, &writeset, NULL, &timeout);
if (ret <= 0)
{
/* 超时或错误 */
close(server_fd);
return TCP_ERR_TIMEOUT;
}
/* 检查连接是否成功 */
int error = 0;
socklen_t len = sizeof(error);
if (getsockopt(server_fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error != 0)
{
close(server_fd);
return TCP_ERR_CONNECT;
}
}
/* 恢复阻塞模式 */
fcntl(server_fd, F_SETFL, flags);
return server_fd;
}
这个函数实现了带超时控制的连接功能。当timeout_sec为0时,使用系统默认超时(阻塞模式);当timeout_sec大于0时,通过设置非阻塞模式配合select实现精确的超时控制。连接成功后自动恢复为阻塞模式。
使用示例:
/* 5秒超时连接 */
int fd = tcp_connect("192.168.1.100", 8080, 5);
if (fd == TCP_ERR_TIMEOUT)
{
printf("连接超时n");
}
else if (fd == TCP_ERR_CONNECT)
{
printf("连接被拒绝n");
}
/* 使用系统默认超时(无限等待) */
int fd = tcp_connect("192.168.1.100", 8080, 0);
3.1.4 数据收发函数
对于数据的收发,封装了四个函数:
tcp_send:普通发送,自动防止SIGPIPE信号
tcp_send_all:确保完整发送所有数据
tcp_blocking_recv:阻塞式接收
tcp_nonblocking_recv:非阻塞式接收,带超时控制
int tcp_send(int conn_sockfd, uint8_t *tx_buf, uint16_t buf_len)
{
#ifdef MSG_NOSIGNAL
return send(conn_sockfd, tx_buf, buf_len, MSG_NOSIGNAL);
#else
return send(conn_sockfd, tx_buf, buf_len, 0);
#endif
}
int tcp_send_all(int conn_sockfd, uint8_t *tx_buf, uint16_t buf_len)
{
uint16_t total_sent = 0;
int sent = 0;
while (total_sent < buf_len)
{
#ifdef MSG_NOSIGNAL
sent = send(conn_sockfd, tx_buf + total_sent, buf_len - total_sent, MSG_NOSIGNAL);
#else
sent = send(conn_sockfd, tx_buf + total_sent, buf_len - total_sent, 0);
#endif
if (sent < 0)
{
if (errno == EINTR)
{
/* 被信号中断,继续发送 */
continue;
}
perror("send");
return TCP_ERR_SEND;
}
elseif (sent == 0)
{
/* 连接已关闭 */
return TCP_ERR_SEND;
}
total_sent += sent;
}
return total_sent;
}
tcp_send使用MSG_NOSIGNAL标志避免SIGPIPE信号。tcp_send_all循环发送直到所有数据都发送完成,处理了EINTR信号中断的情况,确保数据完整性。
int tcp_nonblocking_recv(int conn_sockfd, void *rx_buf, int buf_len, int timeval_sec, int timeval_usec)
{
fd_set readset;
struct timeval timeout = {0, 0};
int maxfd = 0;
int fp0 = 0;
int recv_bytes = 0;
int ret = 0;
timeout.tv_sec = timeval_sec;
timeout.tv_usec = timeval_usec;
FD_ZERO(&readset);
FD_SET(conn_sockfd, &readset);
maxfd = conn_sockfd > fp0 ? (conn_sockfd+1) : (fp0+1);
ret = select(maxfd, &readset, NULL, NULL, &timeout);
if (ret > 0)
{
if (FD_ISSET(conn_sockfd, &readset))
{
if ((recv_bytes = recv(conn_sockfd, rx_buf, buf_len, MSG_DONTWAIT))== -1)
{
perror("recv");
return-1;
}
}
}
else
{
return-1;
}
return recv_bytes;
}
int tcp_blocking_recv(int conn_sockfd, void *rx_buf, uint16_t buf_len)
{
return recv(conn_sockfd, rx_buf, buf_len, 0);
}
阻塞接收函数会一直等待数据到达,适合单一连接的简单场景。
非阻塞接收通过select实现超时控制:
int tcp_nonblocking_recv(int conn_sockfd, void *rx_buf, int buf_len,
int timeval_sec, int timeval_usec)
{
fd_set readset;
struct timeval timeout = {0, 0};
int recv_bytes = 0;
int ret = 0;
timeout.tv_sec = timeval_sec;
timeout.tv_usec = timeval_usec;
FD_ZERO(&readset);
FD_SET(conn_sockfd, &readset);
ret = select(conn_sockfd + 1, &readset, NULL, NULL, &timeout);
if (ret > 0 && FD_ISSET(conn_sockfd, &readset))
{
recv_bytes = recv(conn_sockfd, rx_buf, buf_len, MSG_DONTWAIT);
if (recv_bytes == -1)
{
perror("recv");
return-1;
}
}
else
{
return-1;
}
return recv_bytes;
}
非阻塞接收可以设置秒和微秒级别的超时时间,适合需要轮询多个连接或不想被recv阻塞的场景。
3.2 核心特性总结
通过以上实现,我们的TCP封装库具有以下特点:
简洁易用:每个接口只保留必需参数,使用直观
功能完整:支持超时控制、客户端信息获取、完整发送等高级功能
健壮性强:自动防止SIGPIPE、正确的资源管理、详细的错误码
灵活性好:参数支持NULL,按需获取信息
4. 实战应用示例
我们用一个简单的回声服务器(echo server)来演示这套封装的使用。
4.1 服务端实现
tcp_server.c:
#include "tcp_socket.h"
int main(int argc, char **argv)
{
printf("==================tcp server==================n");
/* 初始化服务器,监听4321端口 */
int server_fd = tcp_init(NULL, 4321);
if (server_fd < 0)
{
printf("tcp_init error! code: %dn", server_fd);
exit(EXIT_FAILURE);
}
printf("Server listening on port 4321...n");
/* 接受客户端连接并获取客户端信息 */
char client_ip[32] = {0};
int client_port = 0;
int client_fd = tcp_accept(server_fd, client_ip, sizeof(client_ip), &client_port);
if (client_fd < 0)
{
printf("tcp_accept error! code: %dn", client_fd);
tcp_close(server_fd);
exit(EXIT_FAILURE);
}
printf("Client connected: %s:%dn", client_ip, client_port);
/* 循环接收数据并回显 */
while (1)
{
char buf[128] = {0};
int recv_len = tcp_blocking_recv(client_fd, buf, sizeof(buf));
if (recv_len <= 0)
{
printf("Client disconnectedn");
tcp_close(client_fd);
tcp_close(server_fd);
exit(EXIT_FAILURE);
}
printf("Received: %sn", buf);
/* 使用tcp_send_all确保完整发送 */
int send_len = tcp_send_all(client_fd, (uint8_t*)buf, strlen(buf));
if (send_len < 0)
{
printf("Send error! code: %dn", send_len);
tcp_close(client_fd);
tcp_close(server_fd);
exit(EXIT_FAILURE);
}
printf("Echo sent: %d bytesn", send_len);
}
tcp_close(server_fd);
return0;
}
服务端的核心代码非常简洁:
- 调用tcp_init初始化服务器,监听4321端口调用tcp_accept等待客户端连接,同时获取客户端IP和端口循环接收数据并使用tcp_send_all完整回显
4.2 客户端实现
tcp_client.c:
#include "tcp_socket.h"
int main(int argc, char **argv)
{
printf("==================tcp client==================n");
if (argc < 3)
{
printf("Usage: ./tcp_client <ip> <port>n");
exit(EXIT_FAILURE);
}
char ip_buf[32] = {0};
int port = 0;
memcpy(ip_buf, argv[1], strlen(argv[1]));
port = atoi(argv[2]);
/* 连接服务器,5秒超时 */
printf("Connecting to %s:%d ...n", ip_buf, port);
int server_fd = tcp_connect(ip_buf, port, 5);
if (server_fd < 0)
{
if (server_fd == TCP_ERR_TIMEOUT)
{
printf("Connection timeout!n");
}
else
{
printf("tcp_connect error! code: %dn", server_fd);
}
exit(EXIT_FAILURE);
}
printf("Connected successfully!n");
/* 循环发送和接收数据 */
while (1)
{
char buf[128] = {0};
printf("nInput message: ");
if (scanf("%s", buf))
{
/* 使用tcp_send_all确保完整发送 */
int send_len = tcp_send_all(server_fd, (uint8_t*)buf, strlen(buf));
if (send_len < 0)
{
printf("tcp_send error! code: %dn", send_len);
tcp_close(server_fd);
exit(EXIT_FAILURE);
}
printf("Sent: %d bytesn", send_len);
bzero(buf, sizeof(buf));
int recv_len = tcp_blocking_recv(server_fd, buf, sizeof(buf));
if (recv_len <= 0)
{
printf("Server disconnectedn");
tcp_close(server_fd);
exit(EXIT_FAILURE);
}
printf("Received: %s (%d bytes)n", buf, recv_len);
}
}
tcp_close(server_fd);
return0;
}
客户端的逻辑同样简洁:
- 从命令行参数获取服务器IP和端口调用tcp_connect连接服务器,5秒超时循环从标准输入读取数据,发送给服务器,然后接收回显的数据完善的错误处理和资源清理
4.3 运行
5.本文代码
https://gitee.com/EmbeddedLinuxZn/tcp_socket
https://github.com/EmbeddedLinuxZn/tcp_socket
6. 总结
这套TCP接口封装方案已经在多个嵌入式项目中使用,它能显著提高开发效率,降低出错概率。
另外,可以根据自己项目的实际需求,在这套封装的基础上进行扩展。比如增加SSL/TLS支持、实现连接池管理、加入心跳检测机制等。
如果觉得文章不错,麻烦帮忙转发,谢谢!
339