当使用 C 语言实现 Socket 编程时,可以通过系统提供的网络库来实现网络通信。以下是一个简单的示例,演示了如何创建一个简单的服务器和客户端,实现客户端向服务器发送消息并接收回复的功能。
服务器端(server.c)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#define PORT 8080
#define MAX_BUFFER_SIZE 1024
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[MAX_BUFFER_SIZE] = {0};
// 创建 Socket
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址和端口
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 绑定 Socket
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Socket bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_socket, 5) == -1) {
perror("Listen failed");
exit(EXIT_FAILURE);
}
printf("Server listening on port %d\n", PORT);
while (1) {
socklen_t client_addr_len = sizeof(client_addr);
// 等待客户端连接
client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_socket == -1) {
perror("Accept failed");
continue;
}
printf("Client connected: %s\n", inet_ntoa(client_addr.sin_addr));
// 接收客户端消息
int bytes_received = recv(client_socket, buffer, MAX_BUFFER_SIZE, 0);
if (bytes_received <= 0) {
perror("Receive failed");
close(client_socket);
continue;
}
// 处理客户端消息
printf("Received from client: %s\n", buffer);
// 发送回复给客户端
const char *reply_message = "Hello, client! I received your message.";
send(client_socket, reply_message, strlen(reply_message), 0);
close(client_socket);
}
close(server_socket);
return 0;
}
客户端(client.c)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8080
#define MAX_BUFFER_SIZE 1024
int main() {
int client_socket;
struct sockaddr_in server_addr;
char buffer[MAX_BUFFER_SIZE] = {0};
// 创建 Socket
if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址和端口
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
perror("Invalid address");
exit(EXIT_FAILURE);
}
// 连接服务器
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Connection failed");
exit(EXIT_FAILURE);
}
// 发送消息给服务器
const char *message = "Hello, server! I am a client.";
send(client_socket, message, strlen(message), 0);
// 接收服务器回复
int bytes_received = recv(client_socket, buffer, MAX_BUFFER_SIZE, 0);
if (bytes_received <= 0) {
perror("Receive failed");
close(client_socket);
exit(EXIT_FAILURE);
}
printf("Received from server: %s\n", buffer);
close(client_socket);
return 0;
}
这是一个简单的 C 语言 Socket 编程示例,演示了一个基本的服务器和客户端之间的消息交互。请注意,这是一个简化的示例,实际应用中可能需要更多的错误处理和安全性措施。
标签:socket,server,client,例子,应用,include,Socket,addr From: https://www.cnblogs.com/keep--fighting/p/17563503.html