实现linux下的基于C语言的一个TCP客户端与服务端通信的测试工具,支持推送指定长度数据的功能(如1MB或10MB),支持慢发送usleep函数的调用,从而验证慢收场景下的数据完整性的代码
时间: 2024-03-08 21:48:21 浏览: 64
好的,下面是一个简单的实现,代码如下:
服务端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
int server_fd, client_fd;
ssize_t len;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[BUFFER_SIZE];
// 创建socket
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
// 设置地址复用
int opt = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) == -1)
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
// 绑定地址和端口
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
if (bind(server_fd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
{
perror("bind");
exit(EXIT_FAILURE);
}
// 监听连接请求
if (listen(server_fd, 5) == -1)
{
perror("listen");
exit(EXIT_FAILURE);
}
printf("Waiting for connections...\n");
// 接受连接请求
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_fd == -1)
{
perror("accept");
exit(EXIT_FAILURE);
}
printf("Connection established: %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
// 接收数据
while ((len = recv(client_fd, buffer, BUFFER_SIZE, 0)) > 0)
{
fwrite(buffer, sizeof(char), len, stdout);
}
if (len == -1)
{
perror("recv");
exit(EXIT_FAILURE);
}
// 关闭连接
close(client_fd);
close(server_fd);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8888
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
int client_fd;
ssize_t len;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
// 创建socket
client_fd = socket(AF_INET, SOCK_STREAM, 0);
if (client_fd == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
// 连接服务器
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
if (connect(client_fd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
{
perror("connect");
exit(EXIT_FAILURE);
}
printf("Connected to server: %s:%d\n", SERVER_IP, PORT);
// 发送数据
int i;
for (i = 0; i < 10; i++)
{
memset(buffer, 'a', BUFFER_SIZE);
usleep(1000000); // 每次发送前暂停1秒,模拟慢发送场景
len = send(client_fd, buffer, BUFFER_SIZE, 0);
if (len == -1)
{
perror("send");
exit(EXIT_FAILURE);
}
printf("Sent %ld bytes of data\n", len);
}
// 关闭连接
close(client_fd);
return 0;
}
```
这个示例程序可以向服务器发送10个1MB大小的数据包,每个数据包之间间隔1秒钟。服务端接收到数据后直接输出到标准输出中。你可以根据自己的需要修改程序中的参数来测试不同的场景。
阅读全文