编写一个基于C/S结构的C语言程序,客户端和服务器可建立基于TCP的连接,客户端可持续向服务器发送信息
时间: 2024-09-13 12:13:55 浏览: 60
C语言打造自己的高性WEB服务器. C to build a high-performance web server. .zip
在C语言中,编写一个基于Client-Server(C/S)结构并且通过TCP通信的应用通常涉及使用socket编程。以下是简化的示例,展示如何创建一个基本的TCP客户端和服务器:
**服务器端(server.c)**:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(struct sockaddr_in);
// 创建套接字并绑定
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(server_socket, (struct sockaddr *)&server_addr, addr_len) == -1) {
perror("Failed to bind socket");
close(server_socket);
exit(EXIT_FAILURE);
}
// 监听
listen(server_socket, 5);
printf("Server listening on port %d...\n", PORT);
while (true) {
// 接受客户端连接
if ((client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &addr_len)) == -1) {
perror("Failed to accept connection");
continue;
}
char buffer[100];
read(client_socket, buffer, sizeof(buffer));
printf("Received message from client: %s\n", buffer);
write(client_socket, "Message received!", strlen("Message received!"));
close(client_socket);
}
return 0;
}
```
**客户端(client.c)**:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define SERVER_IP "localhost"
#define PORT 8080
int main() {
int client_socket;
struct sockaddr_in server_addr;
char message[] = "Hello Server!";
if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);
server_addr.sin_port = htons(PORT);
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Failed to connect to server");
close(client_socket);
exit(EXIT_FAILURE);
}
write(client_socket, message, strlen(message));
printf("Message sent to the server.\n");
char response[100];
read(client_socket, response, sizeof(response));
printf("Server's response: %s\n", response);
close(client_socket);
return 0;
}
```
这个例子中,服务器监听指定端口,接受客户端连接,读取消息并回应。客户端创建套接字,连接到服务器,发送消息,并接收响应。
阅读全文