以下是一个简单的示例代码,用C语言编写一个简单的Socket服务器和客户端:
服务器端代码:
```c
#include
#include
#include
#include
#include
#include
#include
#define PORT 8888
#define BUFFER_SIZE 1024
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[BUFFER_SIZE] = {0};
// 创建socket
if ((server_fd = 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);
// 绑定地址和端口
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_fd, 5) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// 接受客户端连接
if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 从客户端收取数据
if (read(client_fd, buffer, BUFFER_SIZE) < 0) {
perror("read failed");
exit(EXIT_FAILURE);
}
printf("Received message: %s\n", buffer);
// 关闭连接
close(client_fd);
close(server_fd);
return 0;
}
```
客户端代码:
```c
#include
#include
#include
#include
#include
#include
#include
#define PORT 8888
#define SERVER_IP "127.0.0.1"
#define BUFFER_SIZE 1024
int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE] = "Hello from client";
// 创建socket
if ((client_fd = 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 = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
// 连接服务器
if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("connect failed");
exit(EXIT_FAILURE);
}
// 发送数据给服务器
if (write(client_fd, buffer, strlen(buffer)) < 0) {
perror("write failed");
exit(EXIT_FAILURE);
}
// 关闭连接
close(client_fd);
return 0;
}
```
请注意,这只是一个非常简单的示例,用于演示如何使用C语言进行基本的Socket编程。在实际应用中,您可能需要添加更多的错误处理和安全性检查。