//服务端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
#define LISTEN_IP "127.0.0.1" // 可配置的宏定义
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
// 创建 socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 绑定 socket
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(LISTEN_IP); // 使用宏定义配置 IP
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("等待连接...\n");
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 读取数据
read(new_socket, buffer, BUFFER_SIZE);
printf("接收到消息: %s\n", buffer);
// 发送响应
const char *response = "消息已接收";
send(new_socket, response, strlen(response), 0);
printf("响应已发送\n");
// 关闭 socket
close(new_socket);
close(server_fd);
return 0;
}
//client端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
#define SERVER_IP "127.0.0.1"
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char *message = "你好,服务端!";
char buffer[BUFFER_SIZE] = {0};
// 创建 socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket 创建失败 \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 将 IPv4 地址从文本转换为二进制
if (inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr) <= 0) {
printf("\n 无效地址/地址不支持 \n");
return -1;
}
// 连接到服务端
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\n 连接失败 \n");
return -1;
}
// 发送消息
send(sock, message, strlen(message), 0);
printf("消息已发送\n");
// 接收响应
read(sock, buffer, BUFFER_SIZE);
printf("接收到响应: %s\n", buffer);
// 关闭 socket
close(sock);
return 0;
}