用c语言编写代码,实现简单的tcp传输
时间: 2024-11-13 08:21:31 浏览: 10
在C语言中,要实现简单的TCP传输,通常会使用套接字编程。以下是创建一个基本的服务器端和客户端程序的简单示例:
**服务器端(server.c):**
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
int main(int argc, char *argv[]) {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(struct sockaddr_in);
char buffer[1024] = {0};
// 创建套接字并绑定
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket failed");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
// 绑定和监听
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind failed");
exit(EXIT_FAILURE);
}
listen(server_fd, 3);
printf("Server started on port %d\n", PORT);
// 接受连接
while (true) {
if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len)) == -1) {
perror("accept failed");
continue;
}
printf("Accepted connection from %s\n", inet_ntoa(client_addr.sin_addr));
// 读取数据
read(client_fd, buffer, sizeof(buffer));
buffer[strcspn(buffer, "\n")] = '\0'; // 截断字符串
printf("Received message: %s\n", buffer);
// 关闭连接
close(client_fd);
}
return 0;
}
```
**客户端(client.c):**
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8080
int main(int argc, char *argv[]) {
int client_fd;
struct sockaddr_in server_addr;
socklen_t addr_len = sizeof(server_addr);
char message[] = "Hello, Server!";
if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket failed");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
inet_aton(SERVER_IP, &server_addr.sin_addr);
// 连接到服务器
if (connect(client_fd, (struct sockaddr *)&server_addr, addr_len) == -1) {
perror("connect failed");
exit(EXIT_FAILURE);
}
// 发送数据
send(client_fd, message, strlen(message), 0);
printf("Message sent: %s\n", message);
// 读取响应
char response[1024];
read(client_fd, response, sizeof(response));
response[strcspn(response, "\n")] = '\0';
printf("Response received: %s\n", response);
// 关闭连接
close(client_fd);
return 0;
}
```
运行`server.c`作为服务器,`client.c`作为客户端,它们之间可以进行TCP通信。
阅读全文