实现linux下的基于C语言的一个简单的TCP客户端与服务端的通信,支持推送指定长度数据
时间: 2023-12-24 10:02:43 浏览: 75
以下是一个简单的TCP客户端与服务端的通信的示例代码,支持推送指定长度的数据。请注意,此示例代码仅供参考,可能需要根据实际情况进行修改和优化。
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUF_SIZE 100
int main(int argc, char *argv[]) {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[BUF_SIZE];
int str_len, i;
if (argc != 2) {
printf("Usage: %s <port> \n", argv[0]);
exit(1);
}
server_socket = socket(PF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
printf("Server socket creation failed\n");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[1]));
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
printf("Server bind failed\n");
exit(1);
}
if (listen(server_socket, 5) == -1) {
printf("Server listen failed\n");
exit(1);
}
printf("Server is waiting for client\n");
socklen_t client_addr_size = sizeof(client_addr);
client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_size);
if (client_socket == -1) {
printf("Server accept failed\n");
exit(1);
}
printf("Client connected\n");
while (1) {
str_len = read(client_socket, buffer, BUF_SIZE);
if (str_len == 0) {
break;
}
printf("Received message: %s\n", buffer);
write(client_socket, buffer, str_len);
}
close(client_socket);
close(server_socket);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUF_SIZE 100
int main(int argc, char *argv[]) {
int client_socket;
struct sockaddr_in server_addr;
char buffer[BUF_SIZE];
int str_len, i;
if (argc != 4) {
printf("Usage: %s <IP> <port> <length> \n", argv[0]);
exit(1);
}
client_socket = socket(PF_INET, SOCK_STREAM, 0);
if (client_socket == -1) {
printf("Client socket creation failed\n");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
printf("Client connect failed\n");
exit(1);
}
printf("Connected to server\n");
memset(buffer, 'A', atoi(argv[3]));
write(client_socket, buffer, atoi(argv[3]));
printf("Sent message: %s\n", buffer);
str_len = read(client_socket, buffer, BUF_SIZE);
printf("Received message: %s\n", buffer);
close(client_socket);
return 0;
}
```
运行服务端代码:
```
$ ./server 12345
Server is waiting for client
```
运行客户端代码:
```
$ ./client 127.0.0.1 12345 10
Connected to server
Sent message: AAAAAAAAAA
Received message: AAAAAAAAAA
```
说明:
- 服务端代码监听指定端口,并在有客户端连接时接受客户端发送的消息并回复。
- 客户端代码连接指定服务器,并发送指定长度的数据,然后等待服务器回复。
阅读全文