#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define BUFFER_SIZE 1024
#define EXIT_MESSAGE "exit"
void error(const char *message) {
perror(message);
exit(1);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
int server_socket, client_socket;
char buffer[BUFFER_SIZE];
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len;
// 创建服务器套接字
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
error("Error opening socket");
}
// 设置服务器地址结构
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(atoi(argv[1]));
// 绑定服务器套接字到指定端口
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
error("Error binding socket");
}
// 监听连接请求
if (listen(server_socket, 1) < 0) {
error("Error listening");
}
printf("Waiting for a connection...\n");
// 接受客户端连接
client_addr_len = sizeof(client_addr);
client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_socket < 0) {
error("Error accepting connection");
}
printf("Client connected\n");
// 接收和发送消息,直到收到退出消息
while (1) {
// 接收客户端消息
memset(buffer, 0, sizeof(buffer));
if (recv(client_socket, buffer, sizeof(buffer), 0) < 0) {
error("Error receiving data");
}
printf("Client: %s\n", buffer);
// 去除换行符
buffer[strcspn(buffer, "\n")] = '\0';
// 检查退出消息
if (strcmp(buffer, EXIT_MESSAGE) == 0) {
printf("Client exited\n");
break;
}
// 发送消息给客户端
printf("Server: ");
fgets(buffer, sizeof(buffer), stdin);
// 去除换行符
buffer[strcspn(buffer, "\n")] = '\0';
// 检查退出消息
if (strcmp(buffer, EXIT_MESSAGE) == 0) {
if (send(client_socket, buffer, strlen(buffer), 0) < 0) {
error("Error sending data");
}
printf("You exited\n");
break;
}
if (send(client_socket, buffer, strlen(buffer), 0) < 0) {
error("Error sending data");
}
}
// 关闭套接字
close(client_socket);
close(server_socket);
return 0;
}