C语言完成一对一的Socket客户端与服务器程序
时间: 2024-02-18 19:03:40 浏览: 72
好的,我可以帮你解答这个问题。下面是一个简单的 C 语言 Socket 客户端和服务器程序的示例:
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[1024];
// 创建 socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
// 初始化服务器地址结构体
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(8888);
// 绑定 socket 和地址结构体
bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));
// 监听连接请求
listen(server_socket, 10);
printf("Server started, waiting for clients...\n");
// 接收连接请求
socklen_t client_addr_size = sizeof(client_addr);
client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_size);
printf("Client connected: %s\n", inet_ntoa(client_addr.sin_addr));
// 接收数据
memset(buffer, 0, sizeof(buffer));
read(client_socket, buffer, sizeof(buffer));
printf("Received message: %s\n", buffer);
// 发送数据
write(client_socket, "Hello, client!", strlen("Hello, client!"));
// 关闭 socket
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>
int main() {
int client_socket;
struct sockaddr_in server_addr;
char buffer[1024];
// 创建 socket
client_socket = socket(AF_INET, SOCK_STREAM, 0);
// 初始化服务器地址结构体
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(8888);
// 连接服务器
connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));
// 发送数据
write(client_socket, "Hello, server!", strlen("Hello, server!"));
// 接收数据
memset(buffer, 0, sizeof(buffer));
read(client_socket, buffer, sizeof(buffer));
printf("Received message: %s\n", buffer);
// 关闭 socket
close(client_socket);
return 0;
}
```
以上代码实现了一个简单的一对一 Socket 通信,服务器端监听端口 8888,客户端连接服务器,并发送一条消息,服务器接收到消息后回复一条消息。当客户端接收到服务器的回复消息后,程序结束。
阅读全文