用C语言完成一对一Socket客户端和用户端程序
时间: 2024-02-05 20:11:35 浏览: 71
以下是一个简单的基于C语言的Socket客户端和服务器端程序的实现,您可以根据自己的需要进行修改和扩展。
服务端程序
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int server_sock, client_sock, c, read_size;
struct sockaddr_in server, client;
char buffer[BUFFER_SIZE];
// 创建套接字
server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock == -1) {
printf("Failed to create socket.\n");
exit(1);
}
// 设置服务器地址和端口
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
// 绑定套接字到指定地址和端口
if (bind(server_sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
printf("Failed to bind socket.\n");
exit(1);
}
// 监听连接请求
listen(server_sock, MAX_CLIENTS);
printf("Waiting for connections...\n");
c = sizeof(struct sockaddr_in);
// 接受连接请求
client_sock = accept(server_sock, (struct sockaddr *)&client, (socklen_t *)&c);
if (client_sock < 0) {
printf("Failed to accept connection.\n");
exit(1);
}
printf("Client connected.\n");
// 接收客户端发送的数据
while ((read_size = recv(client_sock, buffer, BUFFER_SIZE, 0)) > 0) {
printf("Received message: %s", buffer);
// 处理客户端发送的数据
// ...
// 发送响应数据到客户端
write(client_sock, "OK", strlen("OK"));
}
if (read_size == 0) {
printf("Client disconnected.\n");
} else if (read_size == -1) {
printf("Failed to receive data.\n");
}
return 0;
}
```
客户端程序
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int sock;
struct sockaddr_in server;
char message[BUFFER_SIZE], server_reply[BUFFER_SIZE];
// 创建套接字
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
printf("Failed to create socket.\n");
exit(1);
}
// 设置服务器地址和端口
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(8888);
// 连接到服务器
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
printf("Failed to connect to server.\n");
exit(1);
}
printf("Connected to server.\n");
// 发送数据到服务器
while (1) {
printf("Enter message: ");
fgets(message, BUFFER_SIZE, stdin);
if (send(sock, message, strlen(message), 0) < 0) {
printf("Failed to send data.\n");
exit(1);
}
// 接收服务器响应
if (recv(sock, server_reply, BUFFER_SIZE, 0) < 0) {
printf("Failed to receive data.\n");
exit(1);
}
printf("Server reply: %s", server_reply);
}
close(sock);
return 0;
}
```
注意:上述程序是一个简单的示例,没有进行错误处理和异常情况的处理。在实际开发中,应该对这些情况进行充分考虑和处理。
阅读全文