生成socket通信的客户端和服务器的Linux C代码
时间: 2024-10-23 16:18:04 浏览: 9
良心出品Socket服务端和客户端XML生成与解析java代码.doc
在Linux环境下,使用C语言编写Socket通信的客户端和服务器,需要了解基本的网络编程知识,包括套接字(sockets)、地址族(如AF_INET)、协议族(如SOCK_STREAM)等。下面是一个简单的示例:
**服务器端(server.c):**
```c
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
#define MAX_CLIENTS 5
int main(int argc, char *argv[]) {
int server_fd, client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(client_addr);
// 创建监听套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Failed to create socket");
return 1;
}
// 设置服务器地址
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; // 0.0.0.0表示任意IP
// 绑定并监听
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Failed to bind");
close(server_fd);
return 1;
}
listen(server_fd, MAX_CLIENTS);
printf("Server started on port %d\n", PORT);
while (true) {
// 接受连接
if ((client_sock = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len)) == -1) {
perror("Failed to accept");
continue;
}
// 模拟处理每个新连接
handle_client(client_sock);
close(client_sock);
}
return 0;
}
void handle_client(int client_sock) {
char buffer[1024];
ssize_t bytes_received;
// 读取数据
if ((bytes_received = recv(client_sock, buffer, sizeof(buffer), 0)) > 0) {
printf("Received message from client: %s\n", buffer);
// 可以在此处发送响应给客户端
send(client_sock, "Hello from server!", strlen("Hello from server!"), 0);
} else if (bytes_received == 0) {
printf("Client disconnected.\n");
} else {
perror("Failed to receive data");
}
}
```
**客户端(client.c):**
```c
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8080
int main(int argc, char *argv[]) {
int client_sock;
struct sockaddr_in server_addr;
char message[] = "Hello Server!\n";
if ((client_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Failed to create socket");
return 1;
}
// 设置客户端地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
inet_aton(SERVER_IP, &server_addr.sin_addr); // 将IP转换为二进制形式
// 连接到服务器
if (connect(client_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Failed to connect");
close(client_sock);
return 1;
}
// 发送消息
send(client_sock, message, strlen(message), 0);
printf("Sent message: %s\n", message);
// 接收并显示服务器的回应
char response[1024];
if (recv(client_sock, response, sizeof(response), 0) > 0) {
printf("Server response: %s\n", response);
} else {
perror("Failed to receive response");
}
close(client_sock);
return 0;
}
```
阅读全文