#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <time.h> // 添加时间头文件 int main() { int server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // 创建套接字 if (server_socket < 0) { perror("socket"); return 1; } struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(8000); int iResult = bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)); // 绑定套接字 if (iResult < 0) { perror("bind"); close(server_socket); return 1; } iResult = listen(server_socket, SOMAXCONN); // 监听套接字 if (iResult < 0) { perror("listen"); close(server_socket); return 1; } printf("服务器已启动,等待连接...\n"); int counter = 0; while (1) { struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len); // 接受客户端连接 if (client_socket < 0) { perror("accept"); close(server_socket); return 1; } counter++; printf("客户端 %s:%d 已连接,是今天的第 %d 个客户端。\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), counter); // 添加时间输出 time_t now = time(NULL); struct tm* time_info = localtime(&now); char time_str[20]; strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", time_info); printf("当前时间是:%s\n", time_str); char reply[1024]; sprintf(reply, "你是今天第%d个客户端", counter); send(client_socket, reply, strlen(reply), 0); close(client_socket); } close(server_socket); return 0; }修改成在客户端输出时间
时间: 2024-04-03 07:32:55 浏览: 126
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
int main() {
int client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // 创建套接字
if (client_socket < 0) {
perror("socket");
return 1;
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8000);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
int iResult = connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)); // 连接服务器
if (iResult < 0) {
perror("connect");
close(client_socket);
return 1;
}
char buffer[1024] = {0};
iResult = recv(client_socket, buffer, sizeof(buffer)-1, 0); // 接收服务器的消息
if (iResult < 0) {
perror("recv");
close(client_socket);
return 1;
}
printf("%s\n", buffer); // 输出服务器的消息
time_t now = time(NULL); // 获取当前时间
struct tm* time_info = localtime(&now); // 转换为本地时间
char time_str[20];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", time_info); // 格式化时间字符串
printf("当前时间是:%s\n", time_str); // 输出当前时间
close(client_socket);
return 0;
}
阅读全文